Pointers & Memory · beginner · ~10 min

Pointers and strings

Walk strings via pointer increment.

Lesson

A char * and a char[] decay to the same thing when passed around. Many string library functions are most natural to implement as pointer walks: increment until you hit \0.

const char * declares "the pointed-to chars are read-only". char *const declares "the pointer itself can't be reassigned". Both are useful in APIs to document intent.

Code examples

size_t count_a(const char *s) {
    size_t n = 0;
    for (; *s; s++) if (*s == 'a') n++;
    return n;
}

Common mistakes

  • Modifying a string literal via char *p = "hi"; p[0] = 'H'; — segfault on most systems.
  • Forgetting const: a function that doesn't write should declare const char *.