Strings: char Arrays and \0
C strings are char arrays ending in a zero byte. Measure, copy, join and compare them with string.h.
C · beginner · 8 min · 9 steps · free
What you'll learn
- Store text in char arrays
- Use strlen, strcpy, strcat and strcmp
- Know about the \0 terminator
strings.c
#include <stdio.h>
#include <string.h>
int main(void) {
char name[16] = "Ada";
int len = (int)strlen(name); /* counts characters before the '\0' */
char copy[16];
strcpy(copy, name);
strcat(name, " L.");
int same = strcmp(copy, "Ada") == 0;
char first = name[0];
printf("%s %d %s %d %c\n", name, len, copy, same, first);
return 0;
}
Step by step
- 16 chars of room; "Ada" uses 3 plus the hidden \0 that marks the end.
- strlen counts up to the \0: 3.
- strcpy copies the characters (and \0) into copy.
- strcat appends " L." to name. There must be room!
- strcmp returns 0 when two strings match. == would compare addresses instead.
first is created on the stack with the value 'A'.- It prints
Ada L. 3 Ada 1 A. - The method returns
0. - "Ada L." 3 "Ada" 1 A.
Common mistakes
- Comparing strings with == (compares addresses)
- Overflowing the array with strcat
Best practices
- Make arrays big enough for the text plus \0
Key takeaways
- A C string is a char array ending in \0.
- strlen, strcpy, strcat, strcmp come from string.h.
- Compare with strcmp, never ==.
Check yourself
strcmp("a", "a") returns?
Answer: 0. 0 means equal.
char s[4] can hold which text safely?
Answer: "abc". Room is needed for \0.
← Two-Dimensional Arrays · Pointers: Addresses and * →
More in Arrays and Strings