Pointers & Memory · beginner · ~10 min
Walk a terminated string and return a borrowed pointer without losing its lifetime.
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.
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.
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.
#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
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.
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.