Pointers & Memory · beginner · ~10 min

Pointers and strings

Walk a terminated string and return a borrowed pointer without losing its lifetime.

Overview

A C string is a sequence of characters followed by a zero byte. A pointer into that sequence does not own a new string. Practice finding the terminator and distinguishing a borrowed position from a separately allocated copy.

Core concepts

Walking s until *s == '\0' finds the terminator, provided the input is a valid terminated string. An empty string already starts at its terminator. Length excludes that byte, while storage for a copy includes it.

A search result pointing into the original string is borrowed: do not free it separately or keep it after the original storage expires. A pointer returned from searching a string literal must not be used to modify the literal.

A strchr-style search includes the terminator in the search. Searching for '\0' succeeds at the end, including for an empty string.

Lesson

A C string is a sequence of characters followed by a zero byte. A pointer into that sequence does not own a new string. Practice finding the terminator and distinguishing a borrowed position from a separately allocated copy.

Code examples

#include <stdio.h>
#include <string.h>
int main(void) {
    const char *s = "cat";
    const char *p = strchr(s, 'a');
    if (p != NULL) printf("%s\n", p);
    printf("%zu\n", strlen(s));
    return 0;
}

Expected output on a successful allocation, where applicable:

at
3

Line by line

The search returns a pointer to the a inside cat, so printing from it yields at. The length is three characters; the terminator occupies a fourth byte.

Practice tasks

  1. Predict the length of an empty string and the storage needed to copy it.
  2. Solve String length by pointer.
  3. Solve Find a character, including a search for the terminator.
  4. Optional transfer: Implement strcpy, with the destination capacity guaranteed by the caller.

Summary

Length excludes the terminator; a copy includes it. Search results borrow the input storage. Check for NULL before use and keep the original object alive.

Practice with these exercises