C Strings
In C, a string is simply an array of characters terminated by a special null character '\0'. There is no dedicated string type; instead, strings are handled as char arrays.
String literals in double quotes automatically get a null terminator added by the compiler, but strings built manually must include it yourself.
char name[] = "text";Declaring strings
You can declare a string as `char name[] = "Alice";`, which the compiler sizes to fit the text plus the null terminator. You can also declare a fixed-size buffer like `char name[20];`.
Printing strings
Use %s with printf to print a string. printf reads characters starting from the given address until it finds the null terminator.
#include <stdio.h>
int main() {
char name[] = "Alice";
printf("Hello, %s!\n", name);
return 0;
}Hello, Alice!The string 'Alice' is stored as a char array ending in a hidden \0.
#include <stdio.h>
int main() {
char greeting[20] = "Hi";
printf("%s\n", greeting);
printf("%lu\n", sizeof(greeting));
return 0;
}Hi
20The array is sized 20, but sizeof reports the full array capacity, not the string length.
Key points
- C strings are char arrays ending with a null terminator '\0'.
- String literals automatically include the null terminator.
- %s is the printf specifier for printing strings.
- sizeof() gives array capacity, not the string's actual length.
