CC
IntermediateLesson 9 of 18

Strings as char Arrays – C

Null-terminated strings, string.h, safe copy and format functions.

C has no string type. A string is a char array that ends with the null byte \0. "Hello" therefore occupies 6 bytes. strlen counts up to (excluding) the null byte, while sizeof returns the array size.

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

int main(void) {
    char a[] = "Hello";                 // 6 bytes, size determined automatically
    char b[10] = "World";                // 10 bytes, the rest filled with \0
    char c[] = {'C', '!', '\0'};        // explicit, do not forget the null byte
    printf("%s %zu %zu\n", a, sizeof a, strlen(a));
    printf("%s %zu %zu\n", b, sizeof b, strlen(b));
    printf("%s\n", c);
    a[0] = 'h';                         // modifying is allowed (own array)
    printf("%s\n", a);
    return 0;
}

The standard library <string.h> provides the most important tools. You do not compare with == (that only compares addresses) but with strcmp (0 = equal).

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

int main(void) {
    char s[32] = "Hello";
    strcat(s, " World");                       // append (check the space!)
    printf("%s (%zu)\n", s, strlen(s));       // Hello World (11)
    printf("%d\n", strcmp("apple", "pear") < 0);   // 1: apple comes before pear
    char *pos = strchr(s, 'W');               // find the first 'W'
    printf("%s\n", pos);                      // World
    printf("%s\n", strstr(s, "llo"));         // llo World

    char ziel[8];
    snprintf(ziel, sizeof ziel, "%s-%d", "Value", 12345);   // truncates
    printf("%s\n", ziel);                     // Value-1
    return 0;
}

To understand them, it is worth writing string functions yourself – they are just loops over an array:

#include <stdio.h>

size_t mein_strlen(const char *s) {
    size_t n = 0;
    while (s[n] != '\0') n++;
    return n;
}

void umkehren(char *s) {
    size_t i = 0, j = mein_strlen(s);
    while (i + 1 < j) {
        char t = s[i];
        s[i] = s[j - 1];
        s[j - 1] = t;
        i++;
        j--;
    }
}

int main(void) {
    char text[] = "Hello";
    umkehren(text);
    printf("%s %zu\n", text, mein_strlen(text));   // olleH 5
    return 0;
}
Warningchar *p = "abc"; points to a string literal in read-only memory. p[0] = 'x'; is undefined behavior (usually a crash). Write const char *p = "abc"; – or use an array: char p[] = "abc";.
Warningstrcpy and strcat do not check the destination size. If the source does not fit, a buffer overflow occurs. Prefer snprintf(ziel, sizeof ziel, "%s", quelle) or check strlen(quelle) < sizeof ziel beforehand. strncpy is not a good alternative: if the source is too long, it does not append a null byte.