C Programming Strings
C Programming Strings
C Programming Strings
In C programming, a string is a sequence of characters terminated with a null character \0. For
example:
When the compiler encounters a sequence of characters enclosed in the double quotation
marks, it appends a null character \0 at the end by default.
Memory Diagram
char s[5];
String Declaration in C
String Initialization in C
Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5
characters. This is bad and you should never do this.
char c[100];
c = "C programming"; // Error! array type is not assignable.
The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).
Output
Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the
name string. It's because there was a space after Dennis.
Also notice that we have used the code name instead of &name with scanf().
scanf("%s", name);
This is because name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string,
which is why we don't need to use &.
You can use the fgets() function to read a line of string. And, you can use puts() to display
the string.
Output
Enter name: Tom Hanks
Name: Tom Hanks
Here, we have used fgets() function to read a string from the user.
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input
which is the size of the name string.
Note: The gets() function can also be to take input from the user. However, it is removed from
the C standard.
It's because gets() allows you to input any length of characters. Hence, there might be
a buffer overflow.
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
int main(void) {
char name[] = "Harry Potter";
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}