These are the notes for C Coding Questions, episode 20, placement practice for people who finished the SyntaxPilot C course. Pointer questions, part one: swap two numbers with a function, predict the output of pointer arithmetic, and walk an array with a pointer (and why a[i] is *(a + i)).
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, Linux x86-64: 4-byte int, 8-byte pointers), the SyntaxPilot compiler's C command with warnings on, and every output below is real. Addresses change on every run (the operating system places the program at a random address), so yours will differ. In the input lines below, ⏎ means pressing Enter.
Real-life pictures
| In real life | In C |
|---|---|
| the teacher corrects a photocopy of your notebook; your notebook is unchanged | pass by value: a function gets copies of its arguments |
| a parcel with your home address reaches your real house | a pointer: &x is the address, *p goes there |
| walking to the next train coach moves a whole coach, not one step | p + 1 moves one whole element |
| a postman walks from the first house on the list to the last | walking an array: p from a to a + n |
The idea: addresses and pointers
Every variable lives somewhere in memory, and that place has a number: its address.
&x(the address-of operator, read "ampersand x") gives the address ofx.- A pointer is a variable that holds an address.
int *pdeclares "p points to an int". *p(the dereference operator, read "star p") means "the int at the address in p". Reading*preadsx; writing*p = 5writesx.
#include <stdio.h>
int main() {
int x = 10;
int *p = &x; /* p holds the address of x */
printf("x = %d, *p = %d\n", x, *p);
*p = 25; /* write through the pointer */
printf("x = %d now\n", x);
printf("p points to x: %s\n", p == &x ? "yes" : "no");
return 0;
}
Output:
x = 10, *p = 10
x = 25 now
p points to x: yes
Q1: Swap two numbers with a function
Problem. Write swap so that after swap(...) the two variables have traded values. Read pairs x y, swap, print.
Think out loud.
3 7→x = 7, y = 3;-5 0→x = 0, y = -5;4 4→x = 4, y = 4.- Edge cases: negatives, zero, equal numbers.
The obvious attempt: swap the parameters
#include <stdio.h>
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
int main() {
int x, y;
while (scanf("%d %d", &x, &y) == 2) {
swap(x, y);
printf("x = %d, y = %d\n", x, y);
}
return 0;
}
Input 3 7⏎ -5 0⏎ 4 4⏎:
Output:
x = 3, y = 7
x = -5, y = 0
x = 4, y = 4
Nothing is swapped. Why: C always passes arguments by value. a and b are new variables that start as copies of x and y. swap really swaps the copies, then returns, and the copies disappear. (gcc doesn't warn: the code is legal, just useless.)
Pointer parameters, but the call isn't changed
The fix is to pass the addresses of x and y, so swap can reach the real variables. First, a mistake people make on the way: change the parameters to pointers but forget the & in the call.
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main() {
int x, y;
while (scanf("%d %d", &x, &y) == 2) {
swap(x, y);
printf("x = %d, y = %d\n", x, y);
}
return 0;
}
Compiler output:
main.c: In function ‘main’:
main.c:12:14: warning: passing argument 1 of ‘swap’ makes pointer from integer without a cast [-Wint-conversion]
12 | swap(x, y);
| ^
| |
| int
main.c:3:16: note: expected ‘int *’ but argument is of type ‘int’
3 | void swap(int *a, int *b) {
| ~~~~~^
main.c:12:17: warning: passing argument 2 of ‘swap’ makes pointer from integer without a cast [-Wint-conversion]
12 | swap(x, y);
| ^
| |
| int
main.c:3:24: note: expected ‘int *’ but argument is of type ‘int’
3 | void swap(int *a, int *b) {
| ~~~~~^
Input 3 7⏎ -5 0⏎ 4 4⏎:
Output:
Segmentation fault
Two warnings, then a crash. swap received the number 3 where it expected an address, treated it as address 3, and tried to read memory there. A segmentation fault is the operating system stopping a program that touched memory it doesn't own. (gcc 14 and later make this an error.) A warning in C is very often a real bug: read every one.
The fix: pass the addresses
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main() {
int x, y;
while (scanf("%d %d", &x, &y) == 2) {
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
}
return 0;
}
Input 3 7⏎ -5 0⏎ 4 4⏎:
Output:
x = 7, y = 3
x = 0, y = -5
x = 4, y = 4
Complexity: O(1) time (three assignments), O(1) space (one temporary). Note that scanf("%d", &x) has been doing this all along: it takes &x so it can write into x.
Interview follow-up: swap without a temporary
#include <stdio.h>
void swap_add(int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; }
void swap_xor(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; }
int main() {
int x = 3, y = 7;
swap_add(&x, &y);
printf("add: x = %d, y = %d\n", x, y);
swap_xor(&x, &y);
printf("xor: x = %d, y = %d\n", x, y);
int z = 5;
swap_xor(&z, &z); /* both pointers point to z */
printf("xor with itself: z = %d\n", z);
return 0;
}
Output:
add: x = 7, y = 3
xor: x = 3, y = 7
xor with itself: z = 0
- The
+/-version breaks when*a + *bis bigger thanINT_MAX: signed overflow is undefined behaviour. - The XOR (
^, exclusive or) version sets the value to 0 when both pointers point to the same variable (z ^ zis 0, and the value is lost). Bit tricks are in the bit manipulation episode. - Say both in an interview, then use the temporary: always correct, just as fast.
Q2: Pointer arithmetic: what does this print?
Problem. int a[4] = {10, 20, 30, 40}; int *p = a; Predict the eight lines.
The name of an array, used in an expression, gives the address of its first element, so p = a makes p point to a[0] (this is called the array decaying to a pointer).
The rules you need (operator precedence):
- Postfix
p++binds tighter than unary*, and gives back the old value ofp, then moves it. - Unary
*and prefix++phave the same precedence and group right to left:*++pis*(++p). - Unary
*binds tighter than binary+:*p + 1is(*p) + 1.
Common guesses: *p + 1 → 20, *p++ → 11, (*p)++ → 21. All wrong:
#include <stdio.h>
int main() {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d\n", *p + 1);
printf("%d\n", *(p + 1));
printf("%d\n", *p++);
printf("%d\n", *p);
printf("%d\n", (*p)++);
printf("%d\n", a[1]);
printf("%d\n", *++p);
printf("%d\n", (int)(p - a));
return 0;
}
Output:
11
20
10
20
20
21
30
2
| Line | Means | Prints | Then |
|---|---|---|---|
*p + 1 |
(*p) + 1 = 10 + 1 |
11 | nothing moves |
*(p + 1) |
the next element | 20 | p still at a[0] |
*p++ |
*(p++): the old p |
10 | p moves to a[1] |
*p |
a[1] |
20 | |
(*p)++ |
the int, postfix: old value | 20 | a[1] becomes 21, p doesn't move |
a[1] |
21 | ||
*++p |
*(++p): move first |
30 | p at a[2] |
p - a |
elements between them | 2 |
Subtracting two pointers into the same array gives the number of elements between them (its type is ptrdiff_t, printed with %td, or cast to int as here).
Elements, not bytes: printing real addresses
The obvious attempt prints addresses with %d:
#include <stdio.h>
int main() {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("p = %d\n", p);
printf("p + 1 = %d\n", p + 1);
printf("gap = %d\n", (p + 1) - p);
return 0;
}
Compiler output:
main.c: In function ‘main’:
main.c:6:22: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
6 | printf("p = %d\n", p);
| ~^ ~
| | |
| int int *
| %ls
main.c:7:22: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
7 | printf("p + 1 = %d\n", p + 1);
| ~^ ~~~~~
| | |
| int int *
| %ls
main.c:8:22: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
8 | printf("gap = %d\n", (p + 1) - p);
| ~^ ~~~~~~~~~~~
| | |
| int long int
| %ld
Output:
p = -387618832
p + 1 = -387618828
gap = 1
Three -Wformat warnings. Passing printf an argument of the wrong type is undefined behaviour; here %d read only 4 of the pointer's 8 bytes, so the numbers are just part of each address. Still, the second is 4 more than the first, while the gap says 1.
The fix: %p prints an address (in hexadecimal, base 16, with 0x in front) and expects a void *, a pointer to no particular type, so cast to it. To count bytes, cast both pointers to char * first, because a char is exactly one byte.
#include <stdio.h>
int main() {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("p = %p\n", (void *)p);
printf("p + 1 = %p\n", (void *)(p + 1));
printf("bytes apart: %d\n", (int)((char *)(p + 1) - (char *)p));
printf("elements apart: %d\n", (int)((p + 1) - p));
char s[4] = "abc";
double d[4] = {0};
printf("char +1 moves %d, double +1 moves %d bytes\n",
(int)((char *)(s + 1) - (char *)s), (int)((char *)(d + 1) - (char *)d));
return 0;
}
Output:
p = 0x7ffcee6bd710
p + 1 = 0x7ffcee6bd714
bytes apart: 4
elements apart: 1
char +1 moves 1, double +1 moves 8 bytes
p + k moves k × sizeof(*p) bytes: one whole element per step, like a whole coach. That's why a pointer has a type. Pointer arithmetic is O(1): p + 1000 is one addition.
Pointer arithmetic is only defined inside one array (and one past its end). Comparing or subtracting pointers into different arrays, or moving before the first element, is undefined behaviour.
Q3: Walk an array with a pointer
Problem. Write sum for an array, and print the array backwards, moving a pointer instead of an index. {5, 1, 4, 2, 8, 3} → sum 23, backwards 3 8 2 4 1 5.
Think out loud. How does the function know how many elements there are? And the pointer must never go outside the array.
The obvious attempt: sizeof inside the function
sizeof(a) / sizeof(a[0]) gives the element count of an array (total bytes / bytes per element). It works in main, so the obvious attempt uses it in sum too:
#include <stdio.h>
int sum(int a[]) {
int n = sizeof(a) / sizeof(a[0]);
int total = 0;
for (int i = 0; i < n; i++)
total += a[i];
return total;
}
int main() {
int a[6] = {5, 1, 4, 2, 8, 3};
printf("in main: %d elements\n", (int)(sizeof(a) / sizeof(a[0])));
printf("sum = %d\n", sum(a));
return 0;
}
Compiler output:
main.c: In function ‘sum’:
main.c:4:19: warning: ‘sizeof’ on array function parameter ‘a’ will return size of ‘int *’ [-Wsizeof-array-argument]
4 | int n = sizeof(a) / sizeof(a[0]);
| ^
main.c:3:13: note: declared here
3 | int sum(int a[]) {
| ~~~~^~~
Output:
in main: 6 elements
sum = 6
Why. Passing an array to a function passes only the address of its first element: the array decays to a pointer. A parameter written int a[] (or int a[6]) is int *a. So inside sum, sizeof(a) is the size of a pointer, 8, and 8 / 4 = 2: only 5 and 1 were added.
The fix: pass n, walk the pointer
The caller knows the count, so pass it. Walk p from a to a + n. a + n points one past the end: you may compute it and compare with it, but never read *(a + n). const int * means the function promises not to change the array through p.
#include <stdio.h>
int sum(const int *a, int n) {
int total = 0;
for (const int *p = a; p < a + n; p++)
total += *p;
return total;
}
void print_reverse(const int *a, int n) {
for (const int *p = a + n; p > a; p--)
printf("%d ", *(p - 1));
printf("\n");
}
int main() {
int a[6] = {5, 1, 4, 2, 8, 3};
int n = sizeof(a) / sizeof(a[0]);
printf("in main: %d elements\n", n);
printf("sum = %d\n", sum(a, n));
print_reverse(a, n);
printf("a[2] = %d, *(a + 2) = %d\n", a[2], *(a + 2));
return 0;
}
Output:
in main: 6 elements
sum = 23
3 8 2 4 1 5
a[2] = 4, *(a + 2) = 4
Walking backwards safely. The obvious loop for (p = a + n - 1; p >= a; p--) usually "works", but its last p-- makes p point before a[0], and C doesn't allow even creating that pointer: undefined behaviour. Starting at a + n and printing *(p - 1) while p > a never leaves the allowed range. (It also handles n == 0: nothing is printed.)
a[i] is *(a + i). The C standard defines the subscript a[i] as *((a) + (i)). So indexing is pointer arithmetic, and a pointer walk is not faster than an index loop: use whichever reads clearer. A curiosity that follows from it: 2[a] is *(2 + a), also a[2] (never write that in real code).
Complexity: O(n) time, one step per element; O(1) space, just a pointer.
Complexity summary
| Task | Method | Time | Space |
|---|---|---|---|
| swap | by value | O(1), does nothing | O(1) |
by pointer swap(&x, &y) |
O(1) | O(1) | |
*p, p + k, p - q |
pointer arithmetic | O(1) each | O(1) |
| sum / reverse print | sizeof in the function |
O(1), wrong count | O(1) |
pass n, walk p from a to a + n |
O(n) | O(1) |
Common mistakes (and the real results)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
void swap(int a, int b) |
no error: nothing swapped | pass by value: copies | void swap(int *a, int *b) |
swap(x, y) with int * parameters |
warning: passing argument 1 of 'swap' makes pointer from integer without a cast [-Wint-conversion], then Segmentation fault |
the value 3 used as an address | swap(&x, &y) |
*p + 1 for the next element |
no error: 11, not 20 | * binds before + |
*(p + 1) or p[1] |
*p++ to increment the value |
p moves, the value doesn't change |
postfix ++ binds before * |
(*p)++ |
printf("%d", p) |
warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=] (UB) |
a pointer isn't an int | printf("%p", (void *)p) |
sizeof(a) on an array parameter |
warning: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument], sum = 6 |
the array decayed to a pointer | pass n |
for (p = a + n - 1; p >= a; p--) |
no error, but UB | p goes before a[0] |
for (p = a + n; p > a; p--) with *(p - 1) |
int *p; *p = 5; |
crash or silent corruption (UB) | p points nowhere yet |
point it at something first: p = &x; |
Your turn: reverse an array with two pointers (solution)
Problem. Reverse an array in place using two pointers and no index. {5, 1, 4, 2, 8, 3} → {3, 8, 2, 4, 1, 5}; {7} stays {7}; an empty array stays empty.
Idea. lo at the first element, hi at the last; swap *lo and *hi with today's swap, then lo++, hi--, while lo < hi. For an empty array a + n - 1 would point before a, so return early when n < 2. O(n) time, O(1) space.
Show the solution
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void reverse(int *a, int n) {
if (n < 2) return;
for (int *lo = a, *hi = a + n - 1; lo < hi; lo++, hi--)
swap(lo, hi);
}
void print(const int *a, int n) {
for (const int *p = a; p < a + n; p++) printf("%d ", *p);
printf("\n");
}
int main() {
int a[6] = {5, 1, 4, 2, 8, 3};
int b[1] = {7};
int c[4] = {1, 2, 3, 4};
reverse(a, 6); print(a, 6);
reverse(b, 1); print(b, 1);
reverse(c, 4); print(c, 4);
reverse(a, 0); printf("empty: ok\n");
return 0;
}
Output:
3 8 2 4 1 5
7
4 3 2 1
empty: ok
Practice questions (with solutions)
1. Min and max in one function. Return both through two pointer parameters.
Solution
A function returns one value, but it can write any number of results through pointers (like scanf).
#include <stdio.h>
void min_max(const int *a, int n, int *mn, int *mx) {
*mn = *mx = a[0];
for (const int *p = a + 1; p < a + n; p++) {
if (*p < *mn) *mn = *p;
if (*p > *mx) *mx = *p;
}
}
int main() {
int a[6] = {5, 1, 4, 2, 8, 3};
int lo, hi;
min_max(a, 6, &lo, &hi);
printf("min = %d, max = %d\n", lo, hi);
return 0;
}
Output:
min = 1, max = 8
(It needs n >= 1.) O(n) time, O(1) space.
2. Predict: *p++ += 5. int a[] = {1, 2, 3}; int *p = a; *p++ += 5; What are a[0], a[1], and where does p point?
Solution
*p++ is *(p++): the element at the old p, which is a[0], gets += 5, and p moves to a[1].
#include <stdio.h>
int main() {
int a[] = {1, 2, 3};
int *p = a;
*p++ += 5;
printf("a[0] = %d, a[1] = %d, *p = %d, p - a = %d\n", a[0], a[1], *p, (int)(p - a));
return 0;
}
Output:
a[0] = 6, a[1] = 2, *p = 2, p - a = 1
3. Count the even numbers with a pointer walk.
Solution
#include <stdio.h>
int count_even(const int *a, int n) {
int count = 0;
for (const int *p = a; p < a + n; p++)
if (*p % 2 == 0) count++;
return count;
}
int main() {
int a[8] = {5, 1, 4, 2, 8, 3, -6, 0};
printf("even: %d\n", count_even(a, 8));
return 0;
}
Output:
even: 5
-6 % 2 is 0, so negatives work. O(n), O(1).
4. a[i], *(a + i), p[i] and i[a]. Show that all four name the same element.
Solution
#include <stdio.h>
int main() {
int a[4] = {10, 20, 30, 40};
int *p = a + 1;
printf("%d %d %d %d\n", a[2], *(a + 2), p[1], 2[a]);
printf("p[-1] = %d\n", p[-1]); /* fine: still inside a */
return 0;
}
Output:
30 30 30 30
p[-1] = 10
p[1] is *(p + 1) = a[2]. p[-1] is a[0], allowed because it is still inside the array.
Quick quiz
#include <stdio.h>
int main() {
int a[] = {3, 6, 9, 12};
int *p = a + 1;
printf("%d\n", p[1] + *p);
return 0;
}
(A) 9 (B) 12 (C) 15 (D) 18
Answer
(C) 15. p points to a[1] = 6; p[1] is *(p + 1) = a[2] = 9; 9 + 6 = 15. Brackets work on any pointer.
#include <stdio.h>
int main() {
int a[] = {3, 6, 9, 12};
int *p = a + 1;
printf("%d\n", p[1] + *p);
return 0;
}
Output:
15
Interview questions
- Why can't
void swap(int a, int b)swap? C passes by value; it swaps copies. - What do
&and*do?&xgives the address ofx;*pis the object at the address inp. - Does C have pass by reference? No; you simulate it by passing a pointer (by value).
- What is
p + 1for anint *p? The addresssizeof(int)bytes later: the next int. - Difference between
*p++,(*p)++and*++p? Use then move the pointer; increment the value; move then use. - What does subtracting two pointers give? The number of elements between them (
ptrdiff_t), only within one array. - Why does
sizeofgive the wrong count inside a function? The array parameter is a pointer; pass the size. - Why is
a[i]the same as*(a + i)? The standard defines subscripting that way. - How do you print an address?
printf("%p", (void *)p). - What is a segmentation fault? The OS stopping a program that accessed memory it may not access (e.g. a bad pointer).
Glossary
| Term | Meaning | Example |
|---|---|---|
| Address | The number of a place in memory | 0x7ffd…e0 |
| Pointer | A variable that holds an address | int *p = &x; |
& (address-of) |
Gives a variable's address | &x |
* (dereference) |
The object at the address in a pointer | *p = 5; |
| Dereferencing | Going to the address in a pointer to read or write | t = *a; |
| Pass by value | A function gets copies of its arguments | swap(int a, int b) |
| Pointer parameter | Passing an address so the function can change the caller's variable | swap(&x, &y) |
| Segmentation fault | The OS stopping a program for a bad memory access | swap(x, y) with int * |
-Wint-conversion |
gcc warning: an integer used as a pointer (or back) | makes pointer from integer |
| Pointer arithmetic | Adding/subtracting ints to pointers, in whole elements | p + 1, p - a |
ptrdiff_t |
The type of p - q; printed with %td |
(p + 1) - p |
| Operator precedence | Which operator applies first | *p + 1 is (*p) + 1 |
Postfix / prefix ++ |
p++ gives the old value then adds; ++p adds first |
*p++ vs *++p |
%p |
printf format for an address (a void *) |
printf("%p", (void *)p) |
void * |
A pointer to no particular type | (void *)p |
| Hexadecimal | Base 16, digits 0-9 and a-f; addresses are shown this way | 0x10 = 16 |
-Wformat |
gcc warning: a printf format doesn't match its argument | %d with int * |
sizeof |
The size in bytes of a type or object | sizeof(int) = 4 |
| Array decay | An array used as a value (or passed) becomes a pointer to its first element | sum(a) passes &a[0] |
-Wsizeof-array-argument |
gcc warning: sizeof on an array parameter |
sizeof(a) in sum |
| One past the end | a + n: may be compared, never read |
p < a + n |
const int * |
A pointer through which the int can't be changed | sum(const int *a, int n) |
Subscript a[i] |
Defined as *(a + i) |
p[1] |
| Undefined behaviour (UB) | The C standard makes no promise about the result | p before a[0] |
XOR (^) |
Exclusive or: bit is 1 where the two bits differ | 5 ^ 5 = 0 |
Summary
- C passes by value: to let a function change your variables, pass their addresses:
swap(&x, &y)withint *parameters. Forgetting the&gives-Wint-conversionwarnings and a segmentation fault. p + 1moves one element (sizeof(*p)bytes);p - qcounts elements.*p++uses then moves,(*p)++changes the value,*++pmoves then uses.- Print addresses with
%pand(void *). - An array passed to a function decays to a pointer:
sizeofno longer gives its length, so passnand walkpfromatoa + n(never beforea). a[i]is*(a + i): indexing is pointer arithmetic.
Next episode: Pointer questions II: a dynamic array with malloc and realloc, returning an array from a function (the dangling pointer bug), free and memory leaks.