Sub topic 2
Precedence traps: *p++, (*p)++, and *++p
This chapter assumes basic C syntax, pointer declarations such as int *p, and the ability to compile and run a small program.
Precedence in pointer expressions
Postfix ++ binds tighter than unary *. So *p++ means *(p++): it reads the value at the old address, then advances p. (*p)++ increments the value that p points to and leaves p unchanged. *++p advances p first, then reads.
#include <stdio.h>
int main(void) {
int a[3] = {1, 2, 3};
int *p = a;
int x = *p++;
int y = (*p)++;
printf("%d %d %d %d\n", x, y, a[1], (int)(p - a));
return 0;
}The output is 1 2 3 1.
Two-dimensional arrays
int m[2][3] stores six ints in row-major order. m[i][j] equals *(*(m + i) + j). The name m decays to a pointer to its first row, with type int (*)[3], not int **.
Strings and the null terminator
A C string is a char array that ends with '\0'. The declaration char s[] = "hi"; creates an array of size 3. strlen(s) returns 2 because it counts characters before the terminator.
Pointers to pointers
int **pp = &p; stores the address of the pointer p. The expression **pp reads the int that p points to.
Complex declarations and function pointers
Read a declaration outward from the name, following the parentheses. int *a[3] is an array of three int pointers. int (*b)[3] is a pointer to an array of three ints. int (*f)(int, int) is a pointer to a function that takes two ints and returns an int.
Function calls and the call stack
Each call pushes a stack frame that holds its parameters and local variables. The frame pops when the function returns. Recursion creates one frame per active call, so very deep recursion can overflow the stack.
Dynamic memory: malloc, calloc, realloc, free
malloc(n) returns uninitialized heap memory, or NULL on failure. calloc(count, size) returns zeroed memory. realloc may move the block, so store its result in a temporary pointer before overwriting the original. Every allocation needs exactly one free. After free, the pointer is dangling, so set it to NULL.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *v = calloc(3, sizeof *v);
if (v == NULL) {
return 1;
}
int *tmp = realloc(v, 4 * sizeof *v);
if (tmp == NULL) {
free(v);
return 1;
}
v = tmp;
v[3] = 7;
printf("%d %d\n", v[0], v[3]);
free(v);
v = NULL;
return 0;
}The output is 0 7. The first three elements keep their zeros after realloc.
Exercise
What does this program print? int a[3] = {4, 5, 6}; int p = a; int x = ++p; printf("%d %d\n", x, *p);
Show answer
It prints 5 5. The expression *++p advances p to a[1] and reads 5, so x is 5 and *p is also 5.