What is printed? int a = 5; int *b = &a; int **c = &b; printf("%d %d %d", a, *b, **c); **c = 9; *b += 1; printf(" %d", a);
A pointer is a variable that stores a memory address. Arrays, strings, dynamic memory, call by reference and callbacks all rest on pointers, and pointer arithmetic and pointer-output puzzles are among the most frequently asked C questions.
&x asks 'what is x's house number?', and *p means 'go to the house written on p and look inside'. Pointer arithmetic is walking along the street: for an int pointer, 'the next house' is 4 bytes further on, because every int house is 4 bytes wide.int *p = &x; stores x's address in p, and *p reads or writes x: & takes an address, * dereferences it.p + n moves n × sizeof(*p) bytes; subtracting two pointers into one array gives the number of elements between them.a[i] ≡ *(a + i) ≡ *(i + a) ≡ i[a]. An array name is a non-modifiable pointer to element 0, so a++ is illegal.*p++ is *(p++) — read, then move p. (*p)++ and ++*p change the value; *++p moves p first.int *p[3] is an array of 3 pointers; int (*p)[3] is one pointer to an array of 3 ints; int **pp points to a pointer.const int *p: the data is read-only. int *const p: the pointer is fixed. const int *const p: both.Memory is a long sequence of bytes, each with a numeric address. Every variable occupies one or more bytes, and the address of its first byte is its address. A pointer is a variable whose value is such an address. Pointers let a function change its caller's data, let you walk through arrays and strings, and make dynamic structures such as linked lists possible.
#include <stdio.h>
int main(void)
{
int x = 10;
int *p; /* p is a "pointer to int" */
p = &x; /* & (address-of): p now holds x's address */
printf("%d\n", *p); /* * (dereference): the int at that address: 10 */
*p = 25; /* writing through p changes x */
printf("%d\n", x); /* 25 */
printf("%p %p\n", (void *)&x, (void *)p); /* the same address twice */
printf("%zu %zu\n", sizeof x, sizeof p); /* 4 8 on a 64-bit system */
return 0;
}| Expression | Meaning | Value |
|---|---|---|
&x | the address of x | some address, e.g. 0x7ffc…a4 |
p | the address stored in p | the same as &x |
*p | the object p points to | 10 — it is x itself |
&p | the address of the pointer variable p | a different address |
*&x | dereference the address of x | x, i.e. 10 (* and & cancel) |
* means 'is a pointer': int *p;. In an expression, *p means 'the object at the address in p'. One symbol, two jobs.int* p, q; declares p as a pointer but q as a plain int — the * belongs to each name separately. Write int *p, *q; for two pointers.%p and a (void *) cast. Older textbooks print them with %u and show values like 65524 — that is 16-bit DOS behaviour.A pointer should always hold either a valid address or NULL, the null pointer constant (defined in <stddef.h>, <stdio.h>, <stdlib.h> and others as 0 or ((void *)0)). NULL points to no object, and every valid pointer compares unequal to it, which makes it the standard 'no address' marker: malloc returns NULL on failure, strchr returns NULL when the character is absent, and a linked list ends with a NULL next pointer.
| Kind | How it arises | Example | Prevention |
|---|---|---|---|
| Null pointer | set to NULL on purpose, or returned on failure | int *p = NULL; *p = 1; — crashes | test if (p != NULL) before dereferencing |
| Wild pointer | declared but never initialised, so it holds garbage | int *p; *p = 5; — writes to a random address | initialise every pointer, to NULL if nothing else |
| Dangling pointer | the object it pointed to was freed or went out of scope | free(p); *p = 3;, or returning &local | set p = NULL after free; never return the address of an auto local |
#include <stdio.h>
#include <stdlib.h>
int *bad(void)
{
int local = 42;
return &local; /* WRONG: local dies when bad() returns -> dangling */
}
int *good(void)
{
static int kept = 42; /* static storage outlives the call: safe to return */
return &kept;
}
int main(void)
{
int *q = good();
printf("%d\n", *q); /* 42 */
int *h = malloc(sizeof *h);
if (h == NULL) return 1;
*h = 7;
free(h); /* h is now dangling ... */
h = NULL; /* ... so neutralise it at once */
return 0;
}Adding an integer to a pointer moves it by whole elements, not bytes: if p points to an int, p + 1 points to the next int, 4 bytes further on. In general p + n is the address p + n × sizeof(*p). This scaling is what lets *(p + i) reach the i-th element of an array, whatever the element type.
| Pointer type | p | p + 1 | p + 3 |
|---|---|---|---|
char * | 1000 | 1001 | 1003 |
short * | 1000 | 1002 | 1006 |
int * or float * | 1000 | 1004 | 1012 |
double * | 1000 | 1008 | 1024 |
struct rec * (sizeof 24) | 1000 | 1024 | 1072 |
int (*)[5] (pointer to an array of 5 ints) | 1000 | 1020 | 1060 |
p++, p--, p += n; pointer − pointer within one array, giving an element count of type ptrdiff_t (print with %td); comparing pointers into the same array with <, >, ==; comparing any pointer with NULL.void * (GCC allows it as an extension, treating the step as 1 byte).Subtracting two pointers into the same array gives the number of elements between them, not bytes: for int a[10], &a[7] - &a[2] is 5, although the addresses differ by 20. Casting both to char * first gives the distance in bytes.
| Expression | Parsed as | Effect |
|---|---|---|
*p++ | *(p++) | value 10; then p moves to a[1] |
(*p)++ | increment the pointed-to value | value 10; a[0] becomes 11; p does not move |
*++p | *(++p) | p moves to a[1] first; value 20 |
++*p | ++(*p) | a[0] becomes 11 and the value is 11; p does not move |
++ binds tighter than unary *, and the prefix operators group right-to-left. That alone settles *p++, *++p and ++*p. The classic copy loop while ((*d++ = *s++) != '\0'); works because each *s++ reads the current character and then moves on.An array name used in an expression decays to a pointer to element 0, so a has the value &a[0]. Subscripting is defined through pointer arithmetic: a[i] means *(a + i). Because addition is commutative, *(a + i) equals *(i + a) — which is why the strange-looking i[a] is legal and equal to a[i].
#include <stdio.h>
int main(void)
{
int a[5] = {2, 4, 6, 8, 10};
int *p = a; /* same as p = &a[0] */
int sum = 0;
for (int i = 0; i < 5; i++)
sum += *(p + i); /* identical to p[i] and a[i] */
printf("%d %d %d %d\n", a[2], *(a + 2), 2[a], p[2]); /* 6 6 6 6 */
for (p = a; p < a + 5; p++) /* walk with the pointer itself */
printf("%d ", *p); /* 2 4 6 8 10 */
printf("\nsum = %d\n", sum); /* sum = 30 */
return 0;
}sizeof a = 20: the whole arraya = p; and a++ are errors&a has type int (*)[5], so &a + 1 skips the whole array (20 bytes)sizeof p = 8 on 64-bit: just the pointer&p is the address of the pointer variable, of type int **a, &a[0] and &a all print the same address, yet a + 1 moves 4 bytes (one int) while &a + 1 moves 20 bytes (one whole int[5]). The type, not the numeric value, decides how pointer arithmetic steps.A pointer is itself a variable with an address, so another pointer can point to it. With int x = 5; int *p = &x; int **pp = &p;, *pp is p and **pp is x. Double pointers let a function change its caller's pointer — for instance to update the head of a linked list — and they describe arrays of strings such as char **argv.
#include <stdio.h>
#include <stdlib.h>
void allocate(int **out, int value) /* receives the ADDRESS of a pointer */
{
*out = malloc(sizeof **out); /* changes the caller's pointer */
if (*out != NULL)
**out = value;
}
int main(void)
{
int x = 5, *p = &x, **pp = &p;
printf("%d %d %d\n", x, *p, **pp); /* 5 5 5 */
**pp = 9; /* x is now 9 */
printf("%d\n", x); /* 9 */
int *q = NULL;
allocate(&q, 42); /* q itself gets a new value */
if (q != NULL) printf("%d\n", *q); /* 42 */
free(q);
return 0;
}| Declaration | Read as | sizeof |
|---|---|---|
int *p[3]; | p is an array of 3 pointers to int | 24 (three 8-byte pointers) |
int (*p)[3]; | p is a pointer to an array of 3 ints | 8 (one pointer) |
int **p; | p is a pointer to a pointer to int | 8 |
char *names[] = {"Anu", "Biju"}; | an array of 2 pointers to strings | 16 |
char names[][5] = {"Anu", "Biju"}; | a 2 × 5 array of chars; the strings are copied in | 10 |
int *f(void); | f is a function returning a pointer to int | — |
int (*f)(void); | f is a pointer to a function returning int | 8 |
int (*a[4])(int); | a is an array of 4 pointers to functions taking int and returning int | 32 |
int (*p)[3].[ ] as 'array of' and ( ) as 'function returning'; to the left, read * as 'pointer to'.(*p)[3], p becomes a pointer before the [3] applies.int (*p)[3] → p is a pointer to an array of 3 ints; int *p[3] → p is an array of 3 pointers to int.For int m[3][4], the name m decays to a pointer to its first row, of type int (*)[4]. So m + 1 moves one whole row (16 bytes); *(m + i) is row i, itself an array that decays to int *; *(m + i) + j is the address of m[i][j]; and *(*(m + i) + j) is the element. The pattern extends to three dimensions by adding one more level.
#include <stdio.h>
int main(void)
{
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*row)[3] = m; /* pointer to an array of 3 ints */
printf("%d %d %d\n", *(*(m + 1) + 2), *(*m + 1), **m); /* 6 2 1 */
printf("%d\n", row[1][0]); /* 4 */
printf("%td %td %td\n",
(char *)(m + 1) - (char *)m, /* 12: one row */
(char *)(*m + 1) - (char *)m, /* 4 : one int */
(char *)(&m + 1) - (char *)m); /* 24: the whole array */
return 0;
}int a[3][3][3] holding 1…27 in order, *(*(*(a + 2) + 1) + 2) is a[2][1][2] = 2 × 9 + 1 × 3 + 2 + 1 = 24. Translate each *(X + k) into one index, working from the outside in.A void pointer (void *) is a generic pointer: it can hold the address of any object, and in C it converts to and from any other object pointer type without a cast. That is why malloc returns void * and why memcpy, qsort and bsearch take void * parameters. Because the target type is unknown, a void * cannot be dereferenced or used in arithmetic until it is converted, as in *(int *)vp.
#include <stdio.h>
#include <string.h>
void swap_any(void *a, void *b, size_t size) /* works for any type */
{
unsigned char tmp[64]; /* assumes size <= 64 */
memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);
}
int main(void)
{
int i = 1, j = 2;
double x = 1.5, y = 9.25;
void *vp = &i;
printf("%d\n", *(int *)vp); /* convert first, then dereference: 1 */
swap_any(&i, &j, sizeof i);
swap_any(&x, &y, sizeof x);
printf("%d %d %.2f %.2f\n", i, j, x, y); /* 2 1 9.25 1.50 */
return 0;
}A pointer to a function holds the address of code rather than data: int (*op)(int, int) = add; and then op(2, 3). Function pointers make callbacks possible — qsort calls your comparison function through one — and arrays of them form menu dispatch tables. They are treated in detail in the functions topic.
| Declaration | Can the data change? | Can the pointer change? | Read right to left |
|---|---|---|---|
int *p | yes | yes | p is a pointer to int |
const int *p (same as int const *p) | no | yes | p is a pointer to a const int |
int *const p = &x; | yes | no — and it must be initialised | p is a const pointer to int |
const int *const p = &x; | no | no | p is a const pointer to a const int |
const to the left of * protects the data; const to the right of * protects the pointer. const char *msg is the usual way to pass a string that a function promises not to modify.p[i] as *(p + i), unwrap nested * from the inside out, and remember that postfix ++/-- bind tighter than unary *, while prefix operators apply right to left.p++, --*p) and update a box when a value changes (*p = …, (*p)++).--*++p the decrement changes a pointer stored in an array, so every later statement sees the change.#include <stdio.h>
int main(void)
{
static char *s[] = {"ice", "green", "core", "please"};
static char **ptr[] = {s + 3, s + 2, s + 1, s};
char ***p = ptr;
printf("%s\n", **++p); /* core */
printf("%s\n", *--*++p + 3); /* (an empty line) */
printf("%s\n", *p[-2] + 3); /* ase */
printf("%s\n", p[-1][-1] + 1); /* reen */
return 0;
}How the four lines resolve. At the start p points to ptr[0]. (1) ++p moves p to ptr[1], which holds s + 2, so **p is s[2] = "core". (2) ++p moves p to ptr[2], which holds s + 1; --*p changes ptr[2] itself to s; * then gives s[0] = "ice", and + 3 skips three characters to its terminator — an empty string. (3) p[-2] is ptr[0] = s + 3, so *p[-2] is "please", and + 3 gives "ase". (4) p[-1] is ptr[1] = s + 2, so p[-1][-1] is s[1] = "green", and + 1 gives "reen".
int *p; *p = 5; — writing through a wild pointer.scanf("%d", n); — the missing & makes scanf write to the address equal to n's garbage value.char *s = "abc"; s[0] = 'A'; — modifying a string literal.int *f(void) { int x = 1; return &x; } — a dangling pointer to a dead local.p = &a[5]; on a 5-element array followed by *p — dereferencing one-past-the-end.free(p); *p = 3; — use after free.Try the problem first, then reveal the working one step at a time.
What is printed? int a = 5; int *b = &a; int **c = &b; printf("%d %d %d", a, *b, **c); **c = 9; *b += 1; printf(" %d", a);
An int array a[5] (4-byte int) starts at address 2000. With int *p = a; p += 3; int *q = &a[1];, find p and the element it points to, p − q, (char *)p - (char *)q, a + 4 and &a + 1.
Trace int v[] = {10, 20, 30}, *q = v; int x = *q++; int y = (*q)++; int z = ++*q; int w = *++q; and give x, y, z, w and the final array.
With int a[3][3][3] initialised to 1, 2, …, 27 in order, which expression prints 24: (A) *(*(*(a+2)+2)+2) (B) *(*(*(a+2)+0)+2) (C) *(*(*(a+2)+1)+1) (D) *(*(*(a+2)+1)+2)?
Evaluate step by step: int x = 10, *p = &x, **q = &p; **q += 5; *p *= 2; printf("%d %d", x, **q == *p);
Predict: int a[] = {2, 4, 6, 8, 10}; int *p = a + 1; printf("%d %d %d %d %td", *p, *(p + 2), p[1], *p + 3, p - a);
Describe each declaration in words: (a) int *a[4]; (b) int (*b)[4]; (c) int *c(void); (d) int (*d)(void); (e) char **e; (f) const char *f; (g) char *const g = buf;
On a 64-bit system, double d[4] starts at address 3000 and int m[2][3] (4-byte int) starts at 100. Find d + 2, &d[3] - &d[0], (char *)&d[3] - (char *)&d[0], m + 1, *m + 1 and &m + 1.
Find and fix the pointer bug in each: (a) int *p; *p = 5; (b) int *f(void) { int x = 1; return &x; } (c) int *p = malloc(sizeof *p); free(p); *p = 3; (d) char *s = "abc"; s[0] = 'A'; (e) int n; scanf("%d", n);
int* p, q; only p is a pointer — q is a plain int.*p++ moves the pointer (it is *(p++)); write (*p)++ to increment the value.p + 1 adds sizeof(*p) bytes, not 1, and p - q counts elements, not bytes.a++ and a = p are errors (p++ is fine), and &a + 1 skips the whole array.int *p[3] is an array of 3 pointers; int (*p)[3] is one pointer to an array of 3 ints. const int *p protects the int, int *const p protects the pointer.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
int t[3][3][3] is initialised with the values 1 to 27 in row-major order, so t[0][0][0] = 1 and t[2][2][2] = 27. Which statement prints 24?