Test your understanding of the & operator, * operator, NULL pointers, and the swap function.
int a = 42; int *p = &a; printf("%d\n", *p);
p holds the address of a. *p dereferences the pointer to read the value at that address — the value of a, which is 42.int a = 10; int *p = &a; *p = 20; printf("a = %d\n", a);
*p = 20 writes 20 to the location p points at (which is a). The value of a changes, so we get a = 20.int *p = NULL; printf("%d\n", *p);
*p) is undefined behavior.void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int main(void) { int x = 3, y = 7; swap(&x, &y); printf("x=%d, y=%d\n", x, y); return 0; }
*a = x and *b = y: tmp=3, *a=7, *b=3.int a[3] = {10, 20, 30}; int *p = a; printf("%d\n", p[1]);
a is treated as a pointer to the first element.
p = a makes p point to a[0]p[1] means the same thing as *(p + 1), which equals a[1] = 20[] also works on pointers reflects how closely pointers and arrays are related.
int a[4] = {1, 2, 3, 4}; int *p = a; p++; printf("%d\n", *p);
++ to a pointer advances the address by the size of the pointed-to type.
p points at a[0] (=1)p++, p points at a[1] (it moves forward by sizeof(int) = 4 bytes)*p = a[1] = 2int* advances by sizeof(int); a char* advances by 1 byte. This is the foundational technique for walking through an array with pointers.
void safe_print(int *p) { if (p != NULL) { printf("%d\n", *p); } else { printf("NULL\n"); } } int main(void) { safe_print(NULL); return 0; }
p is NULL, the if (p != NULL) guard prevents *p from running*p without a NULL check would segfault. Guarding with an if is an essential habit for writing safe C code.
int *danger(void) { int x = 42; return &x; // returns the address of a local variable } int main(void) { int *p = danger(); printf("%d\n", *p); return 0; }
x is released from the stack the moment the function returns.
x's lifetime is over by the time the caller uses it*p dereferences a dangling pointer — undefined behaviorx as static, allocate dynamically with malloc, or accept a buffer from the caller as an argument.
int x = 1, y = 2; int *p = &x; int *q = &y; p = q; *p = 99; printf("x=%d, y=%d\n", x, y);
p = q makes p point to the same address as q (it copies the pointer, not the value it points to).
p = q, p points to y (no longer to x)*p = 99 writes 99 to yx is unchanged and stays 1p = q (pointer assignment) and *p = *q (copying the pointed-to value) — they do very different things.