Labs ICT
โญ Pro Login

Strings

Strings in C are just arrays of characters with a special marker at the end. No fancy string type โ€” just char arrays and a null terminator that says "the string ends here."

char Arrays and the Null Terminator

A string ends with \0 (null character, value 0). Every string needs room for it. "Hi" is actually three characters: H, i, \0.


#include 
int main() {
  char word[4] = {'C', 'a', 't', '\0'};
  printf("%s\n", word);
  return 0;
}
    
Try it Yourself โ†’

String Literals

You can use double quotes for string literals. The compiler adds \0 automatically. Much easier than typing each character separately.


#include 
int main() {
  char name[] = "Alice";
  printf("Hello, %s\n", name);
  return 0;
}
    
Try it Yourself โ†’

printf with %s

The %s format specifier prints a string. It reads from the starting address until it hits \0.


#include 
int main() {
  char greeting[] = "Good morning!";
  printf("Message: %s\n", greeting);
  printf("First char: %c\n", greeting[0]);
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What marks the end of a string in C?