---
title: "Pointers and Arrays"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 4
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 4 — Pointers and Arrays

To read a whole number typed at the keyboard, a C program calls `scanf("%d", &n)`. Forget the ampersand, write `scanf("%d", n)`, and the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) warns while the program, with luck, crashes; without luck it writes the number somewhere in memory and carries on. The `&` hands `scanf` the place where `n` lives, so that it can store a value there: [Chapter 3](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#ch-b1-c-functions-and-stack) showed that a function receives copies, and a copy of `n` would be of no use. This chapter is about such places, the addresses of memory, and about the values that hold them, [pointers](#def-b1-pointers-and-arrays-pointer). They are the most powerful feature of C and the source of its worst bugs, and the two are the same thing.

**You already know.**

Memory is a long row of bytes, each with a number, its [address](#def-b1-pointers-and-arrays-pointer). A variable occupies a few consecutive bytes, from a first [address](#def-b1-pointers-and-arrays-pointer) on: an `int` four bytes here, a `double` eight. The school volumes drew it as a row of numbered boxes, and showed that a Python list holds references to its elements rather than the elements themselves.

## 4.1 Addresses and pointers

**Definition 4.1 (Address, pointer, dereferencing).**

The *address* of an object is the address of its first byte; the operator `&` gives it: `&n`. A *pointer* is a value that is an address together with the type of what is stored there; a variable declared `int *p` holds a pointer to an `int`. The operator `*` applied to a pointer, `*p`, designates the object at that address: reading `*p` reads it, assigning to `*p` writes into it. Following a pointer in this way is called *dereferencing* it.

```c
#include <stdio.h>

int main(void)
{
    int n = 5;
    int *p = &n;                         // p holds the address of n
    printf("n = %d, *p = %d\n", n, *p);
    printf("p == &n: %d\n", p == &n);
    *p = 7;                              // writes 7 at that address: into n
    printf("after *p = 7: n = %d\n", n);
    printf("sizeof n = %zu, sizeof p = %zu\n", sizeof n, sizeof p);
    int *nowhere = NULL;
    printf("nowhere == NULL: %d\n", nowhere == NULL);
    return 0;
}
```

***Listing 4.1.** A variable and a [pointer](#def-b1-pointers-and-arrays-pointer) to it code/bachelor-1/04-pointers-and-arrays/listings/addr.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o addr addr.c -lm && ./addr
n = 5, *p = 5
p == &n: 1
after *p = 7: n = 7
sizeof n = 4, sizeof p = 8
nowhere == NULL: 1
```

***Output 4.1.** Writing through `p` changed `n`.*

The type in `int *` matters twice: it tells the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) how many bytes `*p` covers and how to read them, and it lets the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) refuse `double *q = &n;`. A [pointer](#def-b1-pointers-and-arrays-pointer) itself occupies 8 bytes on this machine, whatever it points to, because every [address](#def-b1-pointers-and-arrays-pointer) of a 64-bit process fits in 64 bits. The `*` has two roles in the text: in a declaration it says “[pointer](#def-b1-pointers-and-arrays-pointer) to”; in an expression it dereferences.

![Memory after *p = 7, with made-up addresses (the real ones change from run to run). n occupies the four bytes from address 1000; p, eight bytes from 1008, holds the number 1000. Writing *p writes into the bytes at that number, which are n’s.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-pointers-and-arrays/fig-e40e2e82dc59.svg)

*Memory after `*p = 7`, with made-up addresses (the real ones change from run to run). `n` occupies the four bytes from [address](#def-b1-pointers-and-arrays-pointer) 1000; `p`, eight bytes from 1008, holds the number 1000. Writing `*p` writes into the bytes at that number, which are `n`’s.*

**Definition 4.2 (Null pointer).**

The *null pointer* of a [pointer](#def-b1-pointers-and-arrays-pointer) type, written `NULL` (or 0), compares unequal to the [address](#def-b1-pointers-and-arrays-pointer) of every object and function. It means “points to nothing”: a function that finds nothing returns it, and a [pointer](#def-b1-pointers-and-arrays-pointer) variable not yet given a target should hold it. [Dereferencing](#def-b1-pointers-and-arrays-pointer) the null [pointer](#def-b1-pointers-and-arrays-pointer) is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub).

On this system the first page of memory is never mapped, and [dereferencing](#def-b1-pointers-and-arrays-pointer) `NULL` stops the program at once, the best outcome an [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub) can have ([Section 4.4](#sec-4-4)).

## 4.2 A pointer passed to change the caller’s data

[Passing by value](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-by-value) still holds: a function receives copies. But the copy of an [address](#def-b1-pointers-and-arrays-pointer) is the same [address](#def-b1-pointers-and-arrays-pointer), and through it the function reaches the caller’s variable. The failed `swap` of [Chapter 3](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#ch-b1-c-functions-and-stack) works once it receives addresses.

```c
#include <stdio.h>

void swap(int *a, int *b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void)
{
    int x = 1, y = 2;
    swap(&x, &y);
    printf("after swap: x = %d, y = %d\n", x, y);
    return 0;
}
```

***Listing 4.2.** A swap that swaps code/bachelor-1/04-pointers-and-arrays/listings/swap_ptr.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o swap_ptr swap_ptr.c -lm && ./swap_ptr
after swap: x = 2, y = 1
```

***Output 4.2.** This time `x` and `y` are exchanged.*

![The frames at the end of the fixed swap. Its parameters hold the addresses of main’s variables: writing *a and *b writes into main’s frame. This is the only way a called function reaches the frame of its caller.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-pointers-and-arrays/fig-94a11c648f25.svg)

*The frames at the end of the fixed `swap`. Its parameters hold the addresses of `main`’s variables: writing `*a` and `*b` writes into `main`’s frame. This is the only way a called function reaches the frame of its caller.*

The same device gives a function several results: it returns one, or none, and writes the others through [pointer](#def-b1-pointers-and-arrays-pointer) parameters supplied by the caller. `scanf` works this way: it returns the number of values it converted, and stores each value at the [address](#def-b1-pointers-and-arrays-pointer) it was given.

```c
#include <stdio.h>

void divmod(int a, int b, int *quotient, int *remainder)
{
    *quotient = a / b;
    *remainder = a % b;
}

int main(void)
{
    int q, r;
    divmod(2026, 7, &q, &r);
    printf("2026 = 7 * %d + %d\n", q, r);
    return 0;
}
```

***Listing 4.3.** Two results through two [pointers](#def-b1-pointers-and-arrays-pointer) code/bachelor-1/04-pointers-and-arrays/listings/divmod.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o divmod divmod.c -lm && ./divmod
2026 = 7 * 289 + 3
```

***Output 4.3.** $2026 = 7 \times 289 + 3$.*

```c
#include <stdio.h>

int main(void)
{
    int n;
    if (scanf("%d", &n) != 1) {          // &n: the address of n
        printf("not a number\n");
        return 1;
    }
    printf("%d days = %d weeks and %d days\n", n, n / 7, n % 7);
    return 0;
}
```

***Listing 4.4.** Reading a number: `scanf` stores it at `&n` code/bachelor-1/04-pointers-and-arrays/listings/read_number.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o read_number read_number.c -lm && ./read_number
45 days = 6 weeks and 3 days
```

***Output 4.4.** With 45 on standard input.*

A [pointer](#def-b1-pointers-and-arrays-pointer) parameter that the function only reads from is declared `const int *p`: the function receives a read-only view and the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) refuses `*p = 0`. The `const` documents the contract and is checked: a reader of the [prototype](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-declaration) `int min_max(const int *a, size_t n, int *min, int *max)` knows that the [array](#def-b1-pointers-and-arrays-array) is read and that `*min` and `*max` are written.

## 4.3 Arrays and pointer arithmetic

**Definition 4.3 (Array, array-to-pointer conversion).**

An *array* of C, declared `int a[5]`, is a block of a fixed number of elements of one type, stored contiguously in memory; its size is fixed when it is created. In almost every expression, the name of an array is converted into a [pointer](#def-b1-pointers-and-arrays-pointer) to its first element: this is the *array-to-pointer conversion*. The exceptions are `sizeof a` and `&a`, where `a` stays the whole array.

**Definition 4.4 (Pointer arithmetic).**

If `p` points to element $i$ of an [array](#def-b1-pointers-and-arrays-array), `p + k` points to element $i + k$: *pointer arithmetic* counts in elements, not bytes, so the [address](#def-b1-pointers-and-arrays-pointer) grows by $k$ times the size of an element. The result must point into the [array](#def-b1-pointers-and-arrays-array) or exactly one element past its end. The difference `q - p` of two [pointers](#def-b1-pointers-and-arrays-pointer) into the same [array](#def-b1-pointers-and-arrays-array) is the number of elements between them, of type `ptrdiff_t`. By definition `a[i]` means `*(a + i)`.

```c
#include <stdio.h>

int main(void)
{
    int a[5] = {10, 20, 30, 40, 50};
    for (int i = 0; i <= 5; i++)         // i = 5: the one-past-the-end pointer, never dereferenced
        printf("a + %d is %2td bytes after a\n", i, (char *)(a + i) - (char *)a);
    printf("a[3] = %d, *(a + 3) = %d\n", a[3], *(a + 3));
    int *p = &a[1], *q = &a[4];
    printf("q - p = %td elements\n", q - p);
    printf("sizeof a = %zu bytes, %zu elements\n", sizeof a, sizeof a / sizeof a[0]);
    return 0;
}
```

***Listing 4.5.** The layout of an [array](#def-b1-pointers-and-arrays-array) code/bachelor-1/04-pointers-and-arrays/listings/array_layout.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o array_layout array_layout.c -lm && ./array_layout
a + 0 is  0 bytes after a
a + 1 is  4 bytes after a
a + 2 is  8 bytes after a
a + 3 is 12 bytes after a
a + 4 is 16 bytes after a
a + 5 is 20 bytes after a
a[3] = 40, *(a + 3) = 40
q - p = 3 elements
sizeof a = 20 bytes, 5 elements
```

***Output 4.5.** Elements four bytes apart; `a + 5` is one past the end.*

The [pointer](#def-b1-pointers-and-arrays-pointer) `a + 5` is allowed to exist, to be compared and subtracted, but not to be dereferenced: it is the end mark of every loop of the form `for (p = a; p < a + n; p++)`. A [pointer](#def-b1-pointers-and-arrays-pointer) further away, or before the start, is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub) even if it is never dereferenced.

![An array of five int. The pointer a + k designates element k, 4k bytes from the start; a(k) and *(a + k) are the same element. The position after the last element can be pointed to but holds nothing of the array.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-pointers-and-arrays/fig-a78d8320c813.svg)

*An [array](#def-b1-pointers-and-arrays-array) of five `int`. The [pointer](#def-b1-pointers-and-arrays-pointer) `a + k` designates element $k$, $4k$ bytes from the start; `a[k]` and `*(a + k)` are the same element. The position after the last element can be pointed to but holds nothing of the [array](#def-b1-pointers-and-arrays-array).*

Since an [array](#def-b1-pointers-and-arrays-array) name becomes a [pointer](#def-b1-pointers-and-arrays-pointer), an [array](#def-b1-pointers-and-arrays-array) is never passed to a function: its [address](#def-b1-pointers-and-arrays-pointer) is. A parameter written `int a[]` is a [pointer](#def-b1-pointers-and-arrays-pointer) `int *a`, the function cannot know how many elements follow, and the length must travel in a separate parameter. `sizeof` on such a parameter gives the size of a [pointer](#def-b1-pointers-and-arrays-pointer); GCC warns.

```c
#include <stdio.h>

long sum(int a[], size_t n)              // the same as: long sum(int *a, size_t n)
{
    printf("in sum:  sizeof a = %zu\n", sizeof a);
    long s = 0;
    for (size_t i = 0; i < n; i++)
        s += a[i];
    return s;
}

int main(void)
{
    int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    printf("in main: sizeof days = %zu\n", sizeof days);
    printf("sum = %ld\n", sum(days, sizeof days / sizeof days[0]));
    return 0;
}
```

***Listing 4.6.** An [array](#def-b1-pointers-and-arrays-array) parameter is a [pointer](#def-b1-pointers-and-arrays-pointer) code/bachelor-1/04-pointers-and-arrays/listings/decay.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o decay decay.c -lm && ./decay
decay.c: In function 'sum':
decay.c:6:48: warning: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument]
    6 |     printf("in sum:  sizeof a = %zu\n", sizeof a);
      |                                                ^
decay.c:4:14: note: declared here
    4 | long sum(int a[], size_t n)              // the same as: long sum(int *a, size_t n)
      |          ~~~~^~~
in main: sizeof days = 48
in sum:  sizeof a = 8
sum = 365
```

***Output 4.6.** 48 bytes in `main`, 8 in `sum`.*

This is also why a function can change the elements of an [array](#def-b1-pointers-and-arrays-array) it receives, with no `&` at the call: the [array](#def-b1-pointers-and-arrays-array)’s [address](#def-b1-pointers-and-arrays-pointer) is passed [by value](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-by-value), and the elements are reached through it.

**Definition 4.5 (Row-major order).**

A two-dimensional [array](#def-b1-pointers-and-arrays-array) `int g[h][w]` is an [array](#def-b1-pointers-and-arrays-array) of $h$ rows, each an [array](#def-b1-pointers-and-arrays-array) of $w$ elements, stored one row after the other: this is *row-major order*. Element `g[i][j]` is element $i \cdot w + j$ of the block of $h \cdot w$ elements.

```c
#include <stdio.h>

int main(void)
{
    int g[3][4];
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 4; j++)
            g[i][j] = 10 * i + j;
    int *flat = &g[0][0];
    for (int k = 0; k < 12; k++)
        printf("%d%c", flat[k], k % 4 == 3 ? '\n' : ' ');
    printf("g[2][1] is element %td of the block\n", &g[2][1] - flat);
    printf("sizeof g = %zu, sizeof g[0] = %zu\n", sizeof g, sizeof g[0]);
    return 0;
}
```

***Listing 4.7.** Twelve `int` in a row code/bachelor-1/04-pointers-and-arrays/listings/rowmajor.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o rowmajor rowmajor.c -lm && ./rowmajor
0 1 2 3
10 11 12 13
20 21 22 23
g[2][1] is element 9 of the block
sizeof g = 48, sizeof g[0] = 16
```

***Output 4.7.** `g[2][1]` is element $2 \cdot 4 + 1 = 9$.*

Every [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) lays the rows out this way and lets `flat` walk the twelve elements. Strictly, though, the standard lets a [pointer](#def-b1-pointers-and-arrays-pointer) derived from the row `g[0]` range only over that row and one past its end; walking further, or subtracting a [pointer](#def-b1-pointers-and-arrays-pointer) into row 2, is formally undefined. Portable code indexes `g[i][j]`.

![The array g(3)(4) of , as written in the source and as stored. The shade marks the row. Walking a row is a stride of 1 in memory; walking a column, a stride of 4.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-pointers-and-arrays/fig-c68d9527ac07.svg)

*The [array](#def-b1-pointers-and-arrays-array) `g[3][4]` of [Listing 4.7](#lst-b1-pointers-and-arrays-rowmajor), as written in the source and as stored. The shade marks the row. Walking a row is a stride of 1 in memory; walking a column, a stride of 4.*

## 4.4 Out of bounds

**Definition 4.6 (Out-of-bounds access).**

An *out-of-bounds access* reads or writes through a [pointer](#def-b1-pointers-and-arrays-pointer), or an index, that does not designate an element of the [array](#def-b1-pointers-and-arrays-array) it was derived from. C does not check indices: an out-of-bounds access is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub), and in practice it reads or writes whatever lies at the computed [address](#def-b1-pointers-and-arrays-pointer).

The commonest one is a loop that runs once too many. In the program below, the fifth write of the loop meant for `marks` lands in `bonus`, which on this build is stored just after it; no message, no crash, and a wrong result far from the cause.

```c
#include <stdio.h>

int main(void)
{
    int marks[4] = {12, 15, 9, 14};
    int bonus[4] = {1, 1, 1, 1};
    for (int i = 0; i <= 4; i++)         // one turn too many: i = 4 is outside marks
        marks[i] = 0;
    printf("bonus: %d %d %d %d\n", bonus[0], bonus[1], bonus[2], bonus[3]);
    return 0;
}
```

***Listing 4.8.** One write too many code/bachelor-1/04-pointers-and-arrays/listings/neighbour.c*

```
$ gcc -std=c17 -O0 -o neighbour neighbour.c -lm && ./neighbour
bonus: 0 1 1 1
```

***Output 4.8.** `bonus[0]` was changed by a loop that never names it.*

The [address](#def-b1-pointers-and-arrays-pointer) sanitizer, enabled by `-fsanitize=address`, places a forbidden zone around every [array](#def-b1-pointers-and-arrays-array) and checks every access; `-g` lets it report source lines. The same program, built that way, stops at the bad write and explains it.

```
$ gcc -std=c17 -O0 -g -fsanitize=address neighbour.c -o neighbour
$ ./neighbour
=================================================================
==1000==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffec40 at pc 0x55555555542c bp 0x7fffffffebf0 sp 0x7fffffffebe0
WRITE of size 4 at 0x7fffffffec40 thread T0
    #0 0x55555555542b in main ~/session/neighbour.c:10
  This frame has 2 object(s):
    [32, 48) 'marks' (line 7) <== Memory access at offset 48 overflows this variable
    [64, 80) 'bonus' (line 8)
```

***Output 4.9.** The first lines of the sanitizer’s report (the rest is a map of the forbidden zones). Some lines are left out.*

Read the report from the top: the kind of error (a buffer on the stack overflowed), the access (a write of 4 bytes), the place in the source (line 10, `marks[i] = 0`), then the variable it overflowed: `marks` occupies offsets 32 to 48 of `main`’s frame and the write hit offset 48. As with the undefined-behaviour sanitizer, it can only report the accesses that the run performs.

A [null pointer](#def-b1-pointers-and-arrays-null) dereference needs no sanitizer: the system stops the program.

```c
#include <stdio.h>

int main(int argc, char **argv)
{
    int *p = NULL;
    if (argc > 5)                        // never true here: p stays NULL
        p = (int *)argv;
    printf("about to read *p\n");
    fflush(stdout);
    printf("*p = %d\n", *p);
    return 0;
}
```

***Listing 4.9.** Reading through the [null pointer](#def-b1-pointers-and-arrays-null) code/bachelor-1/04-pointers-and-arrays/listings/nullderef.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra nullderef.c -o nullderef
$ { ./nullderef; } 2>/dev/null; echo "exit status $?"
about to read *p
exit status 139
```

***Output 4.10.** Status 139, as for the [stack overflow](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-stack-overflow) of [Chapter 3](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#ch-b1-c-functions-and-stack): a segmentation fault.*

The status 139 reports a *segmentation fault*: an access to an [address](#def-b1-pointers-and-arrays-pointer) that the process has no right to. It is the system’s protection, not the language’s; an [out-of-bounds access](#def-b1-pointers-and-arrays-oob) that stays inside memory the process owns, as in `neighbour.c`, is not caught at all.

**Safe use.**

Every [array](#def-b1-pointers-and-arrays-array) access in C is a promise by the programmer that the index is in range. Keep the length beside the [array](#def-b1-pointers-and-arrays-array), write loops as `i < n`, never `i <= n`, and run the tests with `-fsanitize=address`. Most of the security flaws in C programs of the last decades started as an out-of-bounds write.

## 4.5 Pointers to functions

**Definition 4.7 (Function pointer).**

A *function pointer* holds the [address](#def-b1-pointers-and-arrays-pointer) of a function together with its type: for example `int (*f)(int, int)` declares `f` as a [pointer](#def-b1-pointers-and-arrays-pointer) to a function taking two `int` and returning an `int`. The name of a function converts to a [pointer](#def-b1-pointers-and-arrays-pointer) to it, and a call `f(6, 7)` through the [pointer](#def-b1-pointers-and-arrays-pointer) calls the function it points to.

```c
#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }

int main(void)
{
    int (*op[3])(int, int) = {add, sub, mul};     // three pointers to functions
    const char sign[3] = {'+', '-', '*'};
    for (int k = 0; k < 3; k++)
        printf("12 %c 5 = %d\n", sign[k], op[k](12, 5));
    int (*f)(int, int) = mul;
    printf("f(6, 7) = %d, (*f)(6, 7) = %d\n", f(6, 7), (*f)(6, 7));
    return 0;
}
```

***Listing 4.10.** A table of operations code/bachelor-1/04-pointers-and-arrays/listings/ops_table.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o ops_table ops_table.c -lm && ./ops_table
12 + 5 = 17
12 - 5 = 7
12 * 5 = 60
f(6, 7) = 42, (*f)(6, 7) = 42
```

***Output 4.11.** The operation is chosen by an index at run time.*

A [function pointer](#def-b1-pointers-and-arrays-function-pointer) lets a function receive part of its algorithm as an argument. The C library’s sorting function, `qsort`, sorts an [array](#def-b1-pointers-and-arrays-array) of any type: it receives the [array](#def-b1-pointers-and-arrays-array)’s [address](#def-b1-pointers-and-arrays-pointer), the number of elements, the size of one element, and a comparison function that it calls with the addresses of two elements. Since `qsort` cannot know the type, those addresses arrive as `const void *`.

**Definition 4.8 (Generic pointer).**

A [pointer](#def-b1-pointers-and-arrays-pointer) to `void`, or *generic pointer*, holds an [address](#def-b1-pointers-and-arrays-pointer) without saying what is stored there. Any object [pointer](#def-b1-pointers-and-arrays-pointer) converts to it and back without loss, with no [cast](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-cast) in C. It cannot be dereferenced nor used in [pointer arithmetic](#def-b1-pointers-and-arrays-arithmetic): it must first be converted to a [pointer](#def-b1-pointers-and-arrays-pointer) to a real type.

```c
int increasing(const void *x, const void *y)     // qsort passes the addresses of two elements
{
    int a = *(const int *)x, b = *(const int *)y;
    return (a > b) - (a < b);                    // negative, zero or positive
}

int decreasing(const void *x, const void *y)
{
    return increasing(y, x);
}

int alphabetical(const void *x, const void *y)   // the elements are pointers to characters
{
    return strcmp(*(const char *const *)x, *(const char *const *)y);
}

int main(void)
{
    int born[] = {1967, 1986, 1963, 2002, 2010, 1951, 2007, 1962};
    const char *first[] = {"Emil", "Quinn", "Rosa", "Sami", "Vera", "Nils", "Caio", "Farid"};
    size_t n = sizeof born / sizeof born[0];
    qsort(born, n, sizeof born[0], increasing);
    for (size_t i = 0; i < n; i++)
        printf("%d%c", born[i], i + 1 < n ? ' ' : '\n');
    qsort(born, n, sizeof born[0], decreasing);
    for (size_t i = 0; i < n; i++)
        printf("%d%c", born[i], i + 1 < n ? ' ' : '\n');
    qsort(first, n, sizeof first[0], alphabetical);
    for (size_t i = 0; i < n; i++)
        printf("%s%c", first[i], i + 1 < n ? ' ' : '\n');
    return 0;
```

***Listing 4.11.** Three orders for `qsort`, three comparators code/bachelor-1/04-pointers-and-arrays/listings/sort_people.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o sort_people sort_people.c -lm && ./sort_people
1951 1962 1963 1967 1986 2002 2007 2010
2010 2007 2002 1986 1967 1963 1962 1951
Caio Emil Farid Nils Quinn Rosa Sami Vera
```

***Output 4.12.** Birth years of eight people of the town, then their first names, in three orders.*

A comparator returns a negative number, zero or a positive number as its first argument comes before, with or after the second. The expression `(a > b) - (a < b)` computes exactly that without the subtraction `a - b`, which could overflow. To sort the names, the elements are [pointers](#def-b1-pointers-and-arrays-pointer) to characters; the comparator receives the addresses of two of them, hence the two levels of [pointer](#def-b1-pointers-and-arrays-pointer) in `*(const char *const *)x`. Strings are the subject of [Chapter 6](https://one-course.com/books/computer-science/3/en/chapter/6-strings-structures-and-files#ch-b1-c-strings-structs-files), and [Chapter 5](https://one-course.com/books/computer-science/3/en/chapter/5-dynamic-memory#ch-b1-dynamic-memory) uses `void *` at every step.

**History — Pointers in the hardware.**

C’s [pointers](#def-b1-pointers-and-arrays-pointer) are a thin layer over the machine. The PDP-11, on which C grew up, addressed memory byte by byte and had instructions that read through a register and then advanced it by the size of the item read, which made `*p++` a single instruction. BCPL and B, C’s ancestors, had a single type, the machine word; C added types to [pointers](#def-b1-pointers-and-arrays-pointer) so that `p + 1` could step by the size of the element, whatever it was.

## 4.6 Exercises

**Exercise 4.1 ★.**

Predict the line printed, following the [pointers](#def-b1-pointers-and-arrays-pointer) one statement at a time.

```c
#include <stdio.h>

int main(void)
{
    int a = 1, b = 2;
    int *p = &a, *q = &b;
    *p = *q + 10;
    p = q;
    *p = *p * 3;
    q = &a;
    *q = *q - *p;
    printf("a = %d, b = %d, *p = %d, *q = %d\n", a, b, *p, *q);
    return 0;
}
```

***Listing 4.12.** Follow the [pointers](#def-b1-pointers-and-arrays-pointer) code/bachelor-1/04-pointers-and-arrays/listings/exo_ptrs.c*

**Solution of Exercise 4.1.**

`*p = *q + 10` writes $2 + 10$ into `a`; `p = q` makes `p` point to `b`; `*p = *p * 3` makes `b` 6; `q = &a`; `*q = *q - *p` makes `a` $12 - 6 = 6$. Now `p` points to `b` and `q` to `a`, both holding 6.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_ptrs exo_ptrs.c -lm && ./exo_ptrs
a = 6, b = 6, *p = 6, *q = 6
```

***Output 4.17.** The output.*

**Exercise 4.2 ★.**

Draw the memory at the end of `main`, as in the figures of this chapter: the [array](#def-b1-pointers-and-arrays-array), the three [pointers](#def-b1-pointers-and-arrays-pointer), and an arrow for each [pointer](#def-b1-pointers-and-arrays-pointer). What does `main` return?

```c
int main(void)
{
    int days[3] = {31, 28, 31};
    int *first = days;
    int *last = &days[2];
    int **which = &last;
    *last = 30;
    *which = first + 1;
    return *last;
}
```

***Listing 4.13.** A [pointer](#def-b1-pointers-and-arrays-pointer) to a [pointer](#def-b1-pointers-and-arrays-pointer) code/bachelor-1/04-pointers-and-arrays/listings/exo_diagram.c*

**Solution of Exercise 4.2.**

`days` holds 31, 28, 30 (the third element was changed through `last`). `first` points to `days[0]`. `which` points to `last`, and `*which = first + 1` changed `last`, which now points to `days[1]`. So three arrows: `first` to `days[0]`, `last` to `days[1]`, `which` to `last`. `main` returns `*last`, that is 28.

**Exercise 4.3 ★.**

Predict the four values printed (a `double` occupies 8 bytes).

```c
#include <stdio.h>

int main(void)
{
    double t[6] = {2.5, -1.0, 4.0, 0.5, 3.5, 1.5};
    double *p = t + 1, *q = &t[5];
    printf("%td %td %.1f %.1f\n", q - p, (char *)q - (char *)p, *(p + 2), p[-1]);
    return 0;
}
```

***Listing 4.14.** [Pointers](#def-b1-pointers-and-arrays-pointer) into an [array](#def-b1-pointers-and-arrays-array) of `double` code/bachelor-1/04-pointers-and-arrays/listings/exo_diff.c*

**Solution of Exercise 4.3.**

`q - p` $= 5 - 1 = 4$ elements, that is $4 \times 8 = 32$ bytes; `*(p + 2)` is `t[3]`, 0.5; `p[-1]` is `*(p - 1)`, that is `t[0]`, 2.5 (allowed: `p - 1` is still inside the [array](#def-b1-pointers-and-arrays-array)).

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_diff exo_diff.c -lm && ./exo_diff
4 32 0.5 2.5
```

***Output 4.18.** The output.*

**Exercise 4.4 ★.**

What does this program print, and why does `length` not compute the length? Rewrite `length`’s caller so that the length is computed where it can be.

```c
#include <stdio.h>

size_t length(const double values[])
{
    return sizeof values / sizeof values[0];
}

int main(void)
{
    double values[10] = {0};
    printf("in main: %zu, in length: %zu\n", sizeof values / sizeof values[0], length(values));
    return 0;
}
```

***Listing 4.15.** The length, computed twice code/bachelor-1/04-pointers-and-arrays/listings/exo_sizeof.c*

**Solution of Exercise 4.4.**

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_sizeof exo_sizeof.c -lm && ./exo_sizeof
exo_sizeof.c: In function 'length':
exo_sizeof.c:6:19: warning: 'sizeof' on array function parameter 'values' will return size of 'const double *' [-Wsizeof-array-argument]
    6 |     return sizeof values / sizeof values[0];
      |                   ^~~~~~
exo_sizeof.c:4:28: note: declared here
    4 | size_t length(const double values[])
      |               ~~~~~~~~~~~~~^~~~~~~~
in main: 10, in length: 1
```

***Output 4.19.** 10 in `main`, 1 in `length`.*

In `length`, `values` is a [pointer](#def-b1-pointers-and-arrays-pointer): $8 / 8 = 1$. Only where the [array](#def-b1-pointers-and-arrays-array) itself is in scope does `sizeof` see its 80 bytes. Compute `size_t n = sizeof values / sizeof values[0];` in `main` and pass `n` to every function that needs the length.

**Exercise 4.5 ★★.**

Explain the warning below. What would `scanf` do with the value it received if the program ran, and why might it crash or might not?

```c
#include <stdio.h>

int main(void)
{
    int n = 0;
    if (scanf("%d", n) == 1)
        printf("read %d\n", n);
    return 0;
}
```

***Listing 4.16.** Reading a number, the wrong way code/bachelor-1/04-pointers-and-arrays/listings/exo_scanf.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -c exo_scanf.c
exo_scanf.c: In function 'main':
exo_scanf.c:7:17: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
    7 |     if (scanf("%d", n) == 1)
      |                ~^   ~
      |                 |   |
      |                 |   int
      |                 int *
```

***Output 4.13.** The [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler)’s warning.*

**Solution of Exercise 4.5.**

`scanf` expects, for `%d`, the [address](#def-b1-pointers-and-arrays-pointer) of an `int`; it received the value of `n`, an `int`, which it would take for an [address](#def-b1-pointers-and-arrays-pointer): here 0, so it would try to store the number at [address](#def-b1-pointers-and-arrays-pointer) 0 and the system would stop the program. Had `n` held another value, `scanf` would have written the number at whatever [address](#def-b1-pointers-and-arrays-pointer) that value names: a crash if the [address](#def-b1-pointers-and-arrays-pointer) is not the program’s, a silent corruption if it is. Passing an argument of the wrong type to `scanf` is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub); the format check of `-Wall` catches it.

**Exercise 4.6 ★★.**

The program below was built with the [address](#def-b1-pointers-and-arrays-pointer) sanitizer. Read the report, give the bug and its fix, and say what the program would have printed without the sanitizer, in the best case.

```c
#include <stdio.h>

double rain[12] = {48.0, 39.5, 41.0, 52.5, 60.0, 45.5, 30.0, 35.5, 50.0, 66.0, 71.5, 58.0};

int main(void)
{
    int n = 12;
    double total = 0;
    for (int i = 0; i <= n; i++)
        total += rain[i];
    printf("average %.2f mm\n", total / n);
    return 0;
}
```

***Listing 4.17.** The average rainfall code/bachelor-1/04-pointers-and-arrays/listings/exo_loop.c*

```
$ gcc -std=c17 -O0 -g -fsanitize=address exo_loop.c -o exo_loop
$ ./exo_loop
=================================================================
==1000==ERROR: AddressSanitizer: global-buffer-overflow on address 0x555555558080 at pc 0x555555555242 bp 0x7fffffffec90 sp 0x7fffffffec80
READ of size 8 at 0x555555558080 thread T0
    #0 0x555555555241 in main ~/session/exo_loop.c:12
0x555555558080 is located 0 bytes to the right of global variable 'rain' defined in 'exo_loop.c:5:8' (0x555555558020) of size 96
SUMMARY: AddressSanitizer: global-buffer-overflow ~/session/exo_loop.c:12 in main
```

***Output 4.14.** The first lines of the report. Some lines are left out.*

**Solution of Exercise 4.6.**

The loop runs for $i = 0, \dots, 12$ and reads `rain[12]`, one element past the end of the global [array](#def-b1-pointers-and-arrays-array) of 12 `double` (96 bytes): a global buffer overflow, a read of 8 bytes. The fix is `i < n`. Without the sanitizer, the program would read whatever follows `rain` in memory; in the best case it is the value 0.0, and the program prints the right average, $597.5 / 12 \approx 49.79$ mm, hiding the bug until the day the memory after `rain` holds something else.

**Exercise 4.7 ★★.**

Write `int min_max(const int *a, size_t n, int *min, int *max)`, which stores the smallest and the largest element of `a[0..n-1]` and returns 0, or returns $-1$ without storing anything when `n` is 0.

**Solution of Exercise 4.7.**

```c
int min_max(const int *a, size_t n, int *min, int *max)
{
    if (n == 0)
        return -1;
    int lo = a[0], hi = a[0];
    for (size_t i = 1; i < n; i++) {
        if (a[i] < lo)
            lo = a[i];
        if (a[i] > hi)
            hi = a[i];
    }
    *min = lo;
    *max = hi;
    return 0;
}
```

*One pass, two results code/bachelor-1/04-pointers-and-arrays/exercises/minmax.c*

The results go into local variables first and are stored only at the end, so nothing is stored when `n` is 0. The test is `tests/minmax_test.c`.

**Exercise 4.8 ★★.**

Write `size_t reverse(int *a, size_t n)`, which reverses an [array](#def-b1-pointers-and-arrays-array) in place with two [pointers](#def-b1-pointers-and-arrays-pointer), one moving forwards from the start and one backwards from the end, and returns the number of swaps it made.

**Solution of Exercise 4.8.**

```c
size_t reverse(int *a, size_t n)
{
    if (n < 2)
        return 0;
    size_t swaps = 0;
    int *left = a, *right = a + n - 1;
    while (left < right) {
        int t = *left;
        *left = *right;
        *right = t;
        left++;
        right--;
        swaps++;
    }
    return swaps;
}
```

*Two [pointers](#def-b1-pointers-and-arrays-pointer) that meet in the middle code/bachelor-1/04-pointers-and-arrays/exercises/reverse.c*

For $n < 2$ there is nothing to do, and `a + n - 1` must not be formed when $n = 0$ (it would point before the [array](#def-b1-pointers-and-arrays-array)). The test `tests/reverse_test.c` checks every $n \leq 9$.

**Exercise 4.9 ★★.**

Predict what the program prints, and explain from the definition of `a[i]` why `2[a]` compiles.

```c
#include <stdio.h>

int main(void)
{
    int a[4] = {7, 8, 9, 10};
    printf("%d %d %d %d\n", a[2], 2[a], *(a + 2), *(2 + a));
    printf("%c\n", "pointer"[3]);
    return 0;
}
```

***Listing 4.18.** `a[2]` and `2[a]` code/bachelor-1/04-pointers-and-arrays/listings/exo_index.c*

**Solution of Exercise 4.9.**

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_index exo_index.c -lm && ./exo_index
9 9 9 9
n
```

***Output 4.20.** The output.*

`a[2]` is by definition `*(a + 2)`, and `2[a]` is `*(2 + a)`: addition of a [pointer](#def-b1-pointers-and-arrays-pointer) and an integer is commutative, so both are the same element. A string literal is an [array](#def-b1-pointers-and-arrays-array) of characters, so `"pointer"[3]` is its fourth character, `n`. Nobody should write `2[a]`.

**Exercise 4.10 ★★★.**

Prove that the [two-pointer](#def-b1-pointers-and-arrays-pointer) reversal of [Exercise 4.8](#exo-b1-pointers-and-arrays-8) is correct and makes exactly $\lfloor n/2 \rfloor$ swaps. State the invariant of its loop in terms of `left - a` and `right - a`.

**Solution of Exercise 4.10.**

Write $L$ = `left - a` and $R$ = `right - a`. Invariant, at each test of the loop: $L + R = n - 1$; the elements at positions $< L$ and $> R$ hold their final values (position $k$ holds the original element $n - 1 - k$); the positions from $L$ to $R$ hold their original elements. Initially $L = 0$, $R = n - 1$: true. A turn with $L < R$ exchanges positions $L$ and $R = n - 1 - L$, which puts both final values in place, then $L$ grows and $R$ shrinks by 1: true again. The loop stops when $L \geq R$; then every position except possibly $L = R$, the middle one (whose final element is its own), is settled: the [array](#def-b1-pointers-and-arrays-array) is reversed. The turns are those with $L < n - 1 - L$, that is $L = 0, 1, \dots$ while $2L < n - 1$: there are $\lceil (n-1)/2 \rceil = \lfloor n/2 \rfloor$ of them, one swap each.

**Exercise 4.11 ★★★.**

Write `generic_max(const void *base, size_t n, size_t size, int (*cmp)(const void *, const void *))`, which returns the [address](#def-b1-pointers-and-arrays-pointer) of a largest element of an [array](#def-b1-pointers-and-arrays-array) of any type, compared by `cmp` with the same contract as for `qsort`, or `NULL` when `n` is 0. Why must it convert `base` to a [pointer](#def-b1-pointers-and-arrays-pointer) to `char`?

**Solution of Exercise 4.11.**

```c
const void *generic_max(const void *base, size_t n, size_t size,
                        int (*cmp)(const void *, const void *))
{
    if (n == 0)
        return NULL;
    const char *bytes = base;            // char: pointer arithmetic counts bytes
    const char *best = bytes;
    for (size_t i = 1; i < n; i++) {
        const char *element = bytes + i * size;
        if (cmp(element, best) > 0)
            best = element;
    }
    return best;
}
```

*The largest element of any [array](#def-b1-pointers-and-arrays-array) code/bachelor-1/04-pointers-and-arrays/exercises/generic_max.c*

[Pointer arithmetic](#def-b1-pointers-and-arrays-arithmetic) is not defined on `void *`, since the size of the element is unknown. A [pointer](#def-b1-pointers-and-arrays-pointer) to `char` counts in bytes, the size of a `char` being 1 by definition, so `bytes + i * size` is the [address](#def-b1-pointers-and-arrays-pointer) of element $i$. The test `tests/generic_max_test.c` uses it on `int`, `double` and [pointers](#def-b1-pointers-and-arrays-pointer) to characters.

**Exercise 4.12 ★★★.**

In an [array](#def-b1-pointers-and-arrays-array) of $n$ elements, the valid [pointers](#def-b1-pointers-and-arrays-pointer) are `a + 0` to `a + n` (one past the end included). Count the pairs $(p, q)$ of valid [pointers](#def-b1-pointers-and-arrays-pointer) with $p \leq q$, and prove your count. What does each such pair describe?

**Solution of Exercise 4.12.**

The valid [pointers](#def-b1-pointers-and-arrays-pointer) are $n + 1$ positions. Pairs with $p < q$: choose two distinct positions, $\binom{n+1}{2}$ ways; pairs with $p = q$: $n + 1$. In all $\binom{n+1}{2} + (n+1) = (n+1)(n+2)/2$. Each pair describes a slice of the [array](#def-b1-pointers-and-arrays-array), the elements from $p$ included to $q$ excluded, with $q - p$ elements; the $n + 1$ pairs with $p = q$ are the empty slices. The test `tests/test_pointer_pairs.py` counts them for $n < 30$.

## 4.7 Problem: A spreadsheet in a flat array

**Problem 4.1.**

Weekend problem — A spreadsheet in a flat array

A small spreadsheet program stores a grid of $h$ rows and $w$ columns of whole numbers in one block of $h \cdot w$ `int`, row after row. The module `grid.c` computes the [address](#def-b1-pointers-and-arrays-pointer) of a cell, sums along a row and a column, and transposes a square grid in place; `sheet.c` tries it on a $4 \times 4$ grid. A colleague’s first transpose, `transpose_bug.c`, was built with the [address](#def-b1-pointers-and-arrays-pointer) sanitizer.

```c
int *cell(int *g, int w, int i, int j)
{
    return g + i * w + j;
}

long row_sum(const int *g, int w, int i)
{
    long s = 0;
    for (const int *p = g + i * w; p < g + (i + 1) * w; p++)
        s += *p;
    return s;
}

long col_sum(const int *g, int w, int h, int j)
{
    long s = 0;
    for (const int *p = g + j; p < g + h * w; p += w)
        s += *p;
    return s;
}

long transpose(int *g, int n)
{
    long swaps = 0;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {            // above the diagonal only
            int t = g[i * n + j];
            g[i * n + j] = g[j * n + i];
            g[j * n + i] = t;
            swaps++;
        }
    return swaps;
}
```

***Listing 4.19.** The module: the index map, two walks, the transpose code/bachelor-1/04-pointers-and-arrays/listings/grid.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o sheet sheet.c grid.c -lm && ./sheet
  0   1   2   3
 10  11  12  13
 20  21  22  23
 30  31  32  33
row 2 sums to 86, column 3 to 72
after the transpose (6 swaps):
  0  10  20  30
  1  11  21  31
  2  12  22  32
  3  13  23  33
n = 1: 0 swaps
n = 2: 1 swaps
n = 3: 3 swaps
n = 4: 6 swaps
n = 5: 10 swaps
n = 6: 15 swaps
n = 7: 21 swaps
n = 8: 28 swaps
```

***Output 4.15.** The grid, its sums, its transpose, and the swaps for $n = 1$ to 8.*

```c
void transpose(int *g, int n)
{
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j <= n; j++) {           // <= : one column too far
            int t = g[i * n + j];
            g[i * n + j] = g[j * n + i];
            g[j * n + i] = t;
        }
}
```

***Listing 4.20.** The colleague’s transpose code/bachelor-1/04-pointers-and-arrays/listings/transpose_bug.c*

```
$ gcc -std=c17 -O0 -g -fsanitize=address transpose_bug.c -o transpose_bug
$ ./transpose_bug
=================================================================
==1000==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffec34 at pc 0x55555555536a bp 0x7fffffffeb90 sp 0x7fffffffeb80
READ of size 4 at 0x7fffffffec34 thread T0
    #0 0x555555555369 in transpose ~/session/transpose_bug.c:10
    #1 0x555555555704 in main ~/session/transpose_bug.c:18
  This frame has 1 object(s):
    [48, 84) 'g' (line 17) <== Memory access at offset 84 overflows this variable
```

***Output 4.16.** The first lines of the sanitizer’s report. Some lines are left out.*

**Part I — The index map.**

1. Let $f(i, j) = i w + j$ for $0 \leq i < h$ , $0 \leq j < w$ . Compute $f(2, 1)$ and $f(3, 3)$ for $w = 4$ .
2. Prove that $f$ takes its values in $[0, hw)$ .
3. Prove that $f$ is injective. (Hint: if $iw + j = i'w + j'$ , look at the remainder of the division by $w$ .)
4. Deduce that $f$ is a bijection onto $[0, hw)$ , and give its inverse with `/` and `%` .
5. Why does `cell` return `g + i * w + j` and not `g + (i * w + j) * sizeof(int)` ?
6. A grid of $h = 50\,000$ rows and $w = 50\,000$ columns: can `i * w + j` be computed in `int` ? What type should the index have?

**Part II — Walking with pointers.**

7. In `row_sum` , which cells does `p` visit, and what is the last value of `p` , which is never dereferenced?
8. In `col_sum` , by how many elements does `p` advance at each step? By how many bytes?
9. Prove that `col_sum` visits exactly the $h$ cells of column $j$ .
10. The last value of `p` in `col_sum` is `g + h * w + j` . Is it allowed to compute it? Rewrite the loop with an index so that no [pointer](#def-b1-pointers-and-arrays-pointer) beyond the end is formed.
11. Check the printed sums: row 2 and column 3 of the grid `10 * i + j` .
12. Give, for the grid `10 * i + j` with $h = w = n$ , the formulas of row sum $i$ and column sum $j$ .

**Part III — The transpose in place.**

13. Show that exchanging `g[i * n + j]` and `g[j * n + i]` for every pair with $i < j$ transposes the grid.
14. Why must the loop not also run over the pairs with $i > j$ ? What would the grid be after it?
15. Count the swaps: prove that there are exactly $n(n-1)/2$ .
16. Check that count against the output for $n = 1$ to 8.
17. Show that the diagonal cells $(i, i)$ never move, and that each other cell moves exactly once.
18. How many swaps would a transpose into a second grid need, and how much extra memory? Compare.

**Part IV — The colleague’s bug.**

19. For $n = 3$ and $i = 0$ , list the pairs of indices that the buggy loop exchanges.
20. Which of them is out of the [array](#def-b1-pointers-and-arrays-array) , and why does the sanitizer report a read of 4 bytes at offset 84 of the frame, given that `g` occupies offsets 48 to 84?
21. Without the sanitizer, which two cells does the exchange with $j = n$ touch, for $i < n - 1$ ? Which of them lies inside the [array](#def-b1-pointers-and-arrays-array) , and what does it hold?
22. For $n = 1$ , which exchange does the buggy loop make? Explain why a test on a $1 \times 1$ grid, without the sanitizer, would not notice the bug.
23. Which line of the report lets you find the faulty line of the source, and which tells you that the caller is `main` ?
24. State the named result of the problem: *the in-place transpose makes exactly $n(n-1)/2$ swaps* , with the range of pairs that achieves it and the counts measured.

**Solution of Problem 4.1.**

**1.** $f(2, 1) = 9$, $f(3, 3) = 15$.

**2.** $f(i, j) \geq 0$, and $f(i, j) \leq (h - 1)w + (w - 1) = hw - 1$.

**3.** If $iw + j = i'w + j'$ with $0 \leq j, j' < w$, both sides have the same remainder when divided by $w$: $j = j'$; then $iw = i'w$ and $i = i'$.

**4.** An injective map from a set of $hw$ elements into a set of $hw$ elements is a bijection. Its inverse is $k \mapsto (k / w, k \bmod w)$, written `(k / w, k % w)` in C.

**5.** [Pointer arithmetic](#def-b1-pointers-and-arrays-arithmetic) counts in elements: `g + k` is already $4k$ bytes after `g`. Multiplying by `sizeof(int)` would go four times too far.

**6.** $50\,000^2 = 2.5 \times 10^9 > 2^{31} - 1$: `i * w` overflows `int`. The index should be computed in `size_t` (or another 64-bit type), and so should the sizes.

**7.** `g + i*w` to `g + i*w + w - 1`, the $w$ cells of row $i$; the final value `g + (i+1)*w` is one past the row: the first cell of the next row, or one past the end of the grid for the last row.

**8.** $w$ elements, that is $4w$ bytes (16 here).

**9.** `p` takes the values `g + j + k*w` for $k = 0, 1, \dots$ while $j + kw < hw$. Since $0 \leq j < w$, that is $k \leq h - 1$: the cells $f(0, j), \dots, f(h-1, j)$, which are column $j$, each once.

**10.** For $j > 0$, `g + h*w + j` lies beyond the one-past-the-end position `g + h*w`: forming it is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub), even unread. With an index: `for (int k = 0; k < h; k++) s += g[k * w + j];`.

**11.** Row 2: $20 + 21 + 22 + 23 = 86$; column 3: $3 + 13 + 23 + 33 = 72$.

**12.** Row $i$: $\sum_j (10i + j) = 10in + n(n-1)/2$. Column $j$: $\sum_i (10i + j) = 5n(n-1) + nj$.

**13.** The transpose $T$ has $T(i, j) = G(j, i)$. The cells off the diagonal fall into pairs $\{(i, j), (j, i)\}$ with $i < j$; one exchange puts both cells of a pair right, the pairs are disjoint, and the diagonal is already right.

**14.** Each pair would be exchanged twice, once as $(i, j)$ and once as $(j, i)$: the grid would come back unchanged.

**15.** One swap per pair $i < j$ of indices among $n$: $\binom{n}{2} = n(n-1)/2$. Or: row $i$ contributes $n - 1 - i$ swaps, and $\sum_{i=0}^{n-1} (n - 1 - i) = n(n-1)/2$.

**16.** $0, 1, 3, 6, 10, 15, 21, 28$ for $n = 1, \dots, 8$: the printed values.

**17.** A diagonal cell has $i = j$, and the loop only reaches pairs with $i < j$. An off-diagonal cell $(i, j)$ belongs to exactly one pair, $\{(\min, \max)\}$, so it moves once.

**18.** A copy writes $n^2$ cells into a second grid of $n^2$ `int`; the transpose in place makes $n(n-1)/2$ swaps (three assignments each) with one extra `int`. For $n = 1000$: 4 MB of extra memory against 4 bytes.

**19.** $j = 1, 2, 3$: indices $(1, 3)$, $(2, 6)$ and $(3, 9)$.

**20.** Index 9 does not exist in an [array](#def-b1-pointers-and-arrays-array) of 9 elements. It lies $9 \times 4 = 36$ bytes after the start of `g`, at offset $48 + 36 = 84$, the first byte past `g`. Line 10 is `g[i * n + j] = g[j * n + i];`, which reads `g[9]`: a read of 4 bytes, reported before any write out of bounds happens.

**21.** `g[i*n + n]`, which is `g[(i+1)*n]`, the first cell of row $i + 1$: inside the [array](#def-b1-pointers-and-arrays-array), holding a value of the grid that the loop should not touch; and `g[n*n + i]`, outside the [array](#def-b1-pointers-and-arrays-array).

**22.** For $n = 1$, $i = 0$ and $j = 1$: the loop exchanges `g[1]` with `g[1]`, a cell outside the [array](#def-b1-pointers-and-arrays-array), with itself. Reading a value and writing it back changes nothing visible, so the $1 \times 1$ grid comes out right and the test passes; only the sanitizer would report the access.

**23.** Frame `#0` gives the faulty line, `transpose_bug.c:10` in `transpose`; frame `#1` gives the caller, `main` at line 18.

**24.** *The in-place transpose makes exactly $n(n-1)/2$ swaps*: it exchanges `g[i*n + j]` and `g[j*n + i]` for the pairs $0 \leq i < j < n$ only, which moves every off-diagonal cell once and leaves the diagonal in place; the run counted $0, 1, 3, 6, 10, 15, 21, 28$ swaps for $n = 1$ to 8, and the colleague’s `j <= n` was caught by the sanitizer at its first access past the grid.
