Skip to content
AgileLogics
5 min read

Strings

Prerequisites: Constants

C has no dedicated string type — a string is a char array ending in a special null terminator byte ('\0') that marks where the text stops.

char name[20] = "Ada";
printf("%s\n", name);          // Ada
printf("%zu\n", strlen(name));  // 3 — strlen does NOT count '\0'

<string.h> provides functions for working with them:

#include <string.h>

char dest[20];
strcpy(dest, "Hello");
strcat(dest, ", world!");
printf("%s\n", dest);            // Hello, world!
printf("%d\n", strcmp("a", "b")); // negative — "a" sorts before "b"

Real-world analogy: think of a string as a row of labeled mail slots, where the null terminator is a "no more mail past this point" sign — every string function relies on finding that sign to know where to stop.

Common mistakes

  • Declaring char name[3] for "Ada" — that's exactly 3 bytes for A, d, a, leaving no room for the null terminator. It needs at least 4.
  • Comparing two strings with == — like in Java, that compares memory addresses, not content. Use strcmp() == 0 instead.

Practice

Declare char city[20] holding your city's name, then print its length with strlen.

Show solution
char city[20] = "Lagos";
printf("%zu\n", strlen(city));