C Programming: Memory, Pointers and the Stack ยท Arrays and Strings

Strings: char Arrays and \0

C strings are char arrays ending in a zero byte. Measure, copy, join and compare them with string.h.

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

  1. 16 chars of room; "Ada" uses 3 plus the hidden \0 that marks the end.
  2. strlen counts up to the \0: 3.
  3. strcpy copies the characters (and \0) into copy.
  4. strcat appends " L." to name. There must be room!
  5. strcmp returns 0 when two strings match. == would compare addresses instead.
  6. first is created on the stack with the value 'A'.
  7. It prints Ada L. 3 Ada 1 A.
  8. The method returns 0.
  9. "Ada L." 3 "Ada" 1 A.