C ยท Chapter 19 of 45

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.

Syntax
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.

Example 1 (c)
#include <stdio.h>

int main() {
  char name[] = "Alice";
  printf("Hello, %s!\n", name);
  return 0;
}
Output
Hello, Alice!

The string 'Alice' is stored as a char array ending in a hidden \0.

Example 2 (c)
#include <stdio.h>

int main() {
  char greeting[20] = "Hi";
  printf("%s\n", greeting);
  printf("%lu\n", sizeof(greeting));
  return 0;
}
Output
Hi
20

The 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.
๐Ÿ’ก Note: Forgetting the null terminator when building strings manually leads to undefined behavior in string functions.

๐Ÿ“ Quick Quiz

1. What marks the end of a C string?

2. Which format specifier prints a string with printf?

3. Is there a dedicated 'string' type in C?