Pointers, arrays and strings in C
How pointer arithmetic works, why array names act like pointers, and how C strings end with a null character.
Pointers are the topic that separates confident C candidates from the rest. Most tricky output questions combine a pointer, an array and a little arithmetic, so it pays to learn exactly how these pieces relate.
What a pointer holds
A pointer stores an address. &x gives the address of x, and *p reads or writes the value at the address held in p.
int x = 10;
int *p = &x;
*p = 20;
printf("%d\n", x); // 20
Changing *p changes x because both refer to the same memory. This is also how a function can modify a caller's variable: pass its address, as in swap(&a, &b). Passing plain values only gives the function copies.
Arrays and pointer arithmetic
In most expressions, an array name converts to a pointer to its first element. Adding 1 to a pointer moves it by one element, not one byte, so arr[i] and *(arr + i) mean the same thing.
int arr[] = {5, 10, 15};
int *q = arr;
printf("%d %d\n", *(q + 1), q[2]); // 10 15
Watch precedence: *q + 1 reads the first element and adds 1, giving 6, while *(q + 1) reads the second element. The array name itself cannot be reassigned, but a pointer variable can.
Strings are char arrays
A C string is an array of characters that ends with the null character '\0'. The literal "hi" therefore takes three bytes.
sizeofon an array gives its total size in bytes, including the null character.strlencounts characters up to, but not including, the null character.- Compare strings with
strcmp, not==, which compares addresses.
char name[] = "code";
printf("%zu %zu\n", sizeof(name), strlen(name)); // 5 4
Never write past the end of an array. C does not check bounds, so the program may print garbage, crash, or seem fine until much later.
Tracing habit
For pointer questions, draw a box for each variable with its address and value, and move the pointer arrow as the code runs. It takes a minute and prevents most mistakes.
More in Programming