C/C++ Arena

Strings in C

How C strings work as char arrays ending in a null terminator, plus strlen, strcpy, strcmp and safe copying.

C has no string type. A string is a char array with a '\0' (null terminator) after the last character, so "cat" needs 4 bytes.

<string.h> has the helpers: strlen (length without the terminator), strcmp (compare, returns 0 when equal), strcpy and strcat (copy and append, which don't check the destination's size).

Never compare strings with ==: that compares addresses. And make sure the destination has room for the terminator, or use snprintf, which always stays within the size you give it.

Example

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[16];
    snprintf(name, sizeof name, "%s-%d", "player", 7);
    printf("%s has %zu chars\n", name, strlen(name));
    printf("%d\n", strcmp(name, "player-7") == 0);
    return 0;
}

Output:

player-7 has 8 chars
1

Watch it run: A string ends at the null terminator

Practice it