ZetCode

K&R C pointers and arrays

last modified December 5, 2026 K&R C 1978

In C, pointers and arrays are closely related. Any operation done with an array index can also be done with a pointer, and an array name in an expression is a pointer to the first element. This article shows the arithmetic that connects the two, and then builds arrays of pointers, the data structure behind lists of strings. It assumes the arrays and pointers articles.

Pointer arithmetic

If p points to an element of an array, p + 1 points to the next element and p + i to the element i places further. The compiler scales i by the size of the element, so the arithmetic counts elements, not bytes.

ptr_arith.c
#include <stdio.h>

int main()
{
    static int a[] = { 10, 20, 30, 40, 50 };
    int *p;

    p = &a[0];          /* the same as p = a */
    printf("*p = %d\n", *p);
    printf("*(p + 1) = %d\n", *(p + 1));
    printf("*(a + 3) = %d, a[3] = %d\n", *(a + 3), a[3]);

    p = a + 2;          /* p points to a[2] */
    printf("p[0] = %d, p[1] = %d, p[-1] = %d\n", p[0], p[1], p[-1]);
    printf("3[a] = %d\n", 3[a]);
    return 0;
}

The name of an array is the address of its first element, so p = a and p = &a[0] are the same. The compiler translates a[i] into *(a + i); it works the same way with a pointer, so p[1] is the element after the one p points to, and p[-1] the one before it. Because addition does not care about the order of its operands, 3[a] means *(3 + a) and is legal, if useless.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ptr_arith ptr_arith.c
$ ./ptr_arith
*p = 10
*(p + 1) = 20
*(a + 3) = 40, a[3] = 40
p[0] = 30, p[1] = 40, p[-1] = 20
3[a] = 40

Walking an array

A pointer can step through an array with ++. This is the usual style of C: instead of an index, a pointer moves from element to element until it reaches the end.

walk.c
#include <stdio.h>

/* sum n ints starting at v */
int sum(v, n)
int *v;
int n;
{
    int s;

    s = 0;
    while (n-- > 0)
        s += *v++;
    return s;
}

int main()
{
    static int a[] = { 4, 8, 15, 16, 23, 42 };
    int *p;

    for (p = a; p < a + 6; p++)
        printf("%d ", *p);
    printf("\n");

    printf("all six: %d\n", sum(a, 6));
    printf("a[2] to a[4]: %d\n", sum(a + 2, 3));
    printf("last two: %d\n", sum(&a[4], 2));
    return 0;
}

The loop in main stops when p reaches a + 6, the address just past the last element. Such an address may be computed and compared, but not used for indirection. *v++ reads the element v points to and then moves v on; the ++ applies to the pointer, not to the element. A function can be given part of an array: a + 2 and &a[4] are the addresses of later elements, and the function cannot tell the difference.

$ gcc -std=c89 -pedantic -Wall -Wextra -o walk walk.c
$ ./walk
4 8 15 16 23 42 
all six: 108
a[2] to a[4]: 54
last two: 65

Array parameters are pointers

An array argument passes the address of its first element. The parameter that receives it is a pointer, even when it is declared as an array: int v[]; and int *v; mean the same in a parameter declaration.

array_param.c
#include <stdio.h>

/* v is declared as an array, but it is a pointer */
int report(v)
int v[];
{
    printf("in report: sizeof v = %d\n", (int) sizeof v);
    v++;                /* legal: v is a pointer variable */
    printf("v[0] is now %d\n", v[0]);
    return 0;
}

int main()
{
    static int a[] = { 5, 6, 7, 8 };

    printf("in main: sizeof a = %d\n", (int) sizeof a);
    report(a);
    return 0;
}

In main, sizeof a is the size of the whole array. In report, sizeof v is the size of a pointer, and GCC warns that this is probably not what the programmer wanted. Unlike an array name, the parameter is a variable and can be incremented. A function therefore cannot find out the length of an array it receives; the length must be passed along or marked by a special last element.

$ gcc -std=c89 -pedantic -Wall -Wextra -o array_param array_param.c
array_param.c: In function ‘report’:
array_param.c:7:55: warning: ‘sizeof’ on array function parameter ‘v’ will return size of ‘int *’ [-Wsizeof-array-argument]
    7 |     printf("in report: sizeof v = %d\n", (int) sizeof v);
      |                                                       ^
array_param.c:5:5: note: declared here
    5 | int v[];
      |     ^
$ ./array_param
in main: sizeof a = 16
in report: sizeof v = 8
v[0] is now 6

On the PDP-11 an int and a pointer both have two bytes, so the array of four elements has eight bytes and the parameter two.

$ cc array_param.c
$ a.out
in main: sizeof a = 8
in report: sizeof v = 2
v[0] is now 6

Pointer subtraction

Two pointers into the same array can be subtracted. The result is the number of elements between them, so subtracting the start of the array from a pointer to an element gives the index of the element.

subtract.c
#include <stdio.h>

/* return the index of the first negative element, or -1 */
int first_negative(v, n)
int *v;
int n;
{
    int *p;

    for (p = v; p < v + n; p++)
        if (*p < 0)
            return p - v;
    return -1;
}

int main()
{
    static int balance[] = { 120, 45, 0, -30, 15, -80 };
    int i;

    i = first_negative(balance, 6);
    printf("first negative at %d: %d\n", i, balance[i]);
    i = first_negative(balance + 4, 2);
    printf("in the last two at %d\n", i);
    i = first_negative(balance, 3);
    printf("in the first three at %d\n", i);
    return 0;
}

first_negative walks with a pointer and returns p - v when it finds a negative balance. The index is relative to the start the function was given: in the last two elements of balance the negative one is at index 1. Pointers can also be compared with < and the other relational operators, as the loop condition does, as long as both point into the same array.

$ gcc -std=c89 -pedantic -Wall -Wextra -o subtract subtract.c
$ ./subtract
first negative at 3: -30
in the last two at 1
in the first three at -1

Two pointers

Many array algorithms work from both ends at once. Two pointers, one moving forward and one moving back, express this directly.

two_ptrs.c
#include <stdio.h>

/* reverse n ints in place with two pointers */
int reverse(v, n)
int *v;
int n;
{
    int *left, *right;
    int t;

    left = v;
    right = v + n - 1;
    while (left < right) {
        t = *left;
        *left++ = *right;
        *right-- = t;
    }
    return 0;
}

int main()
{
    static int a[] = { 1, 2, 3, 4, 5, 6, 7 };
    int *p;

    reverse(a, 7);
    for (p = a; p < a + 7; p++)
        printf("%d ", *p);
    printf("\n");

    reverse(a + 1, 3);
    for (p = a; p < a + 7; p++)
        printf("%d ", *p);
    printf("\n");
    return 0;
}

left starts at the first element and right at the last. Each step swaps the two elements and moves both pointers towards the middle; the loop ends when they meet. *left++ = *right stores through left and then advances it. The second call reverses only the three elements from a[1] to a[3].

$ gcc -std=c89 -pedantic -Wall -Wextra -o two_ptrs two_ptrs.c
$ ./two_ptrs
7 6 5 4 3 2 1 
7 4 5 6 3 2 1 

Arrays of pointers

Pointers are variables, so they can be stored in arrays. An array of character pointers is the usual way to keep a set of strings. A string constant such as "Monday" is an array of characters ending with '\0'; in an expression it gives a pointer to its first character.

day_names.c
#include <stdio.h>

/* return the name of day n, 1 to 7 */
char *day_name(n)
int n;
{
    static char *name[] = {
        "no such day",
        "Monday", "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday", "Sunday"
    };

    if (n < 1 || n > 7)
        return name[0];
    return name[n];
}

int main()
{
    int i;

    for (i = 1; i <= 7; i++)
        printf("%d %s\n", i, day_name(i));
    printf("9 %s\n", day_name(9));
    return 0;
}

name is an array of eight pointers, each pointing to a string constant stored elsewhere in the program. It is static, so it is initialized once and kept between calls. day_name returns a char *, one of these pointers; element 0 serves as the answer for invalid day numbers.

$ gcc -std=c89 -pedantic -Wall -Wextra -o day_names day_names.c
$ ./day_names
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday
9 no such day

Pointers to pointers

A pointer to an element of an array of pointers is a pointer to a pointer. It is declared with two stars: char **pp says that **pp is a char.

ptr_to_ptr.c
#include <stdio.h>

/* print the strings of a list that ends with 0 */
int print_list(list)
char **list;
{
    while (*list != 0)
        printf("%s\n", *list++);
    return 0;
}

int main()
{
    static char *planets[] = { "Mercury", "Venus", "Earth", "Mars", 0 };
    char **pp;
    char *t;

    pp = &planets[1];
    printf("*pp = %s, **pp = %c\n", *pp, **pp);

    t = planets[0];             /* swap two pointers, not the text */
    planets[0] = planets[3];
    planets[3] = t;
    print_list(planets);
    return 0;
}

*pp is the second pointer of the array, the string Venus, and **pp its first character. print_list receives the array as a char ** and walks it until the 0 that ends the list. The swap exchanges two pointers; the strings themselves do not move. Sorting a list of strings by swapping pointers is much cheaper than moving the text, which the text processing article uses to sort lines.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ptr_to_ptr ptr_to_ptr.c
$ ./ptr_to_ptr
*pp = Venus, **pp = V
Mars
Venus
Earth
Mercury

Pointer arrays and two-dimensional arrays

A list of strings can also be stored in a two-dimensional array of characters. The two forms are used the same way, table[i] and ptrs[i] both give a string, but they are laid out differently in memory.

ragged.c
#include <stdio.h>

/* the same names as a two-dimensional array and as pointers */
char table[][12] = { "ant", "bee", "caterpillar", "dragonfly" };
char *ptrs[] = { "ant", "bee", "caterpillar", "dragonfly" };

int main()
{
    int i;

    printf("sizeof table = %d\n", (int) sizeof table);
    printf("sizeof ptrs  = %d\n", (int) sizeof ptrs);
    for (i = 0; i < 4; i++)
        printf("%s %s\n", table[i], ptrs[i]);
    return 0;
}

table has four rows of twelve characters, 48 bytes, whatever the length of the names; every row must be as long as the longest name. ptrs holds only four pointers, 32 bytes on x86-64; the strings lie elsewhere and take just the space they need, so the rows can have different lengths.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ragged ragged.c
$ ./ragged
sizeof table = 48
sizeof ptrs  = 32
ant ant
bee bee
caterpillar caterpillar
dragonfly dragonfly

On the PDP-11 the array of pointers is only eight bytes, while the character table keeps its 48.

$ cc ragged.c
$ a.out
sizeof table = 48
sizeof ptrs  = 8
ant ant
bee bee
caterpillar caterpillar
dragonfly dragonfly

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Options to Request or Suppress Warnings

In this article we have connected pointers and arrays in K&R C: pointer arithmetic, a[i] as *(a + i), walking arrays with pointers, array parameters, pointer subtraction and comparison, arrays of pointers, pointers to pointers, and pointer arrays compared with two-dimensional arrays. The next article, K&R C strings, applies all of this to character strings.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.