C String
C String
Memory Diagram
Arrays and strings are second-class citizens in C; they do not support the
assignment operator once it is declared. For example,
char c[100];
c=- // Error! array type is not assignable.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
You can use the fgets() function to read a line of string. And, you can use puts() to
display the string.
Example 2: fgets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output:
Strings can be passed to a function in a similar way as arrays. Learn more about
passing arrays to a function.
#include <stdio.h>
void displayString(char str[]);
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);
}
Example 4: Strings and Pointers
#include <stdio.h>
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
}
Loop Through a String
You can also loop through the characters of a string, using a for loop:
Example 5:
#include <stdio.h>
int main() {
char carName[] = "Volvo";
int i;
return 0;
}
Commonly Used String Functions