ZetCode

K&R C pointers

last modified December 5, 2026 K&R C 1978

A pointer is a variable that holds the address of another variable. Pointers let a function change the variables of its caller, and they are the way C works with arrays and strings. C came from system programming on small machines, and its pointers are close to the hardware: an address is a number, and the language lets the programmer compute with it. This article covers single variables; the next one, pointers and arrays, covers pointer arithmetic.

Address and indirection

The unary operator & gives the address of a variable. The unary operator *, the indirection operator, gives the variable that a pointer points to. The declaration int *p; says that *p is an int, and so p is a pointer to an int.

pointer.c
#include <stdio.h>

int main()
{
    int x, y;
    int *p;     /* p points to an int */

    x = 7;
    p = &x;     /* p now holds the address of x */
    y = *p;     /* y gets the int that p points to */
    printf("x = %d, y = %d, *p = %d\n", x, y, *p);

    *p = 12;    /* changes x */
    printf("x = %d, y = %d, *p = %d\n", x, y, *p);

    p = &y;     /* p points elsewhere */
    printf("*p = %d\n", *p);
    return 0;
}

After p = &x, the expression *p can be used wherever x can: y = *p reads x, and *p = 12 changes it. y got a copy of the value, so it keeps 7. A pointer can be pointed at another variable at any time. The declaration of a pointer is meant as a mnemonic: it reads like the expression that uses it.

$ gcc -std=c89 -pedantic -Wall -Wextra -o pointer pointer.c
$ ./pointer
x = 7, y = 7, *p = 7
x = 12, y = 7, *p = 12
*p = 7

Pointer expressions

*p is an ordinary int variable, so it can appear in any expression and on the left side of any assignment. The indirection operator binds more tightly than the arithmetic operators.

ptr_expr.c
#include <stdio.h>

int main()
{
    int n, m;
    int *p, *q;

    n = 10;
    p = &n;

    m = *p + 1;         /* the value n + 1 */
    printf("m = %d\n", m);

    *p = *p * 2;        /* n doubled */
    *p += 5;
    printf("n = %d\n", n);

    ++*p;               /* increments n */
    (*p)++;             /* so does this; the parentheses are needed */
    printf("n = %d\n", n);

    q = p;              /* q points to n as well */
    *q = 0;
    printf("n = %d, *p = %d\n", n, *p);
    return 0;
}

*p + 1 takes the value p points to and adds 1. ++*p increments the variable, because the unary operators group from right to left. In (*p)++ the parentheses are needed: *p++ would increment the pointer instead, which the next article uses to walk through arrays. A pointer can be copied into another pointer of the same type; then both point to the same variable.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ptr_expr ptr_expr.c
$ ./ptr_expr
m = 11
n = 25
n = 27
n = 0, *p = 0

Pointer arguments

C passes arguments by value: a function receives copies and cannot change the caller's variables. To let a function change them, the caller passes their addresses, and the function works through pointers.

swap.c
#include <stdio.h>

/* swaps its own copies only */
int swap_values(a, b)
int a, b;
{
    int t;

    t = a;
    a = b;
    b = t;
    return 0;
}

/* swaps the variables that pa and pb point to */
int swap(pa, pb)
int *pa, *pb;
{
    int t;

    t = *pa;
    *pa = *pb;
    *pb = t;
    return 0;
}

int main()
{
    int x, y;

    x = 1;
    y = 2;
    swap_values(x, y);
    printf("x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

swap_values exchanges its own copies a and b, which disappear when it returns, and x and y stay the same. swap receives the addresses &x and &y and exchanges the variables they point to. The parameters are declared int *pa, *pb; in the old-style declaration list, like any other parameter type.

$ gcc -std=c89 -pedantic -Wall -Wextra -o swap swap.c
$ ./swap
x = 1, y = 2
x = 2, y = 1

Returning several values

A function returns only one value. Pointer arguments give it more: the caller passes the addresses of variables, and the function stores its results there.

min_max.c
#include <stdio.h>

/* store the smallest and the largest of v[0]..v[n-1] */
int min_max(v, n, lo, hi)
int v[];
int n;
int *lo, *hi;
{
    int i;

    *lo = *hi = v[0];
    for (i = 1; i < n; i++) {
        if (v[i] < *lo)
            *lo = v[i];
        if (v[i] > *hi)
            *hi = v[i];
    }
    return 0;
}

int main()
{
    static int temps[] = { 14, 9, 17, 21, 12, 8, 19 };
    int low, high;

    min_max(temps, 7, &low, &high);
    printf("lowest %d, highest %d\n", low, high);
    return 0;
}

min_max stores the smallest and the largest temperature into the variables of main through lo and hi. The multiple assignment *lo = *hi = v[0] starts both with the first element. The array is passed without &, because an array name already stands for the address of its first element.

$ gcc -std=c89 -pedantic -Wall -Wextra -o min_max min_max.c
$ ./min_max
lowest 8, highest 21

Reading numbers

An input function must return two things: the value it has read and whether there was a value at all. A common solution returns the status as the result of the function and stores the value through a pointer.

read_ints.c
#include <stdio.h>

#define MAX 10

/* read the next integer into *pn; return 0 if there is none */
int read_int(pn)
int *pn;
{
    int c, sign;

    while ((c = getchar()) == ' ' || c == '\t' || c == '\n')
        ;
    sign = 1;
    if (c == '-' || c == '+') {
        if (c == '-')
            sign = -1;
        c = getchar();
    }
    if (c < '0' || c > '9') {   /* end of input or not a number */
        if (c != EOF)
            ungetc(c, stdin);
        return 0;
    }
    for (*pn = 0; c >= '0' && c <= '9'; c = getchar())
        *pn = 10 * *pn + (c - '0');
    *pn = sign * *pn;
    if (c != EOF)
        ungetc(c, stdin);
    return 1;
}

int main()
{
    int v[MAX];
    int i, n, sum;

    for (n = 0; n < MAX && read_int(&v[n]); n++)
        ;
    sum = 0;
    for (i = 0; i < n; i++)
        sum += v[i];
    printf("%d numbers, sum %d\n", n, sum);
    return 0;
}

read_int skips white space, handles a sign, and builds the number digit by digit in *pn. The character after the number is pushed back with ungetc, as in the character input article. It returns 1 when it has read a number and 0 at the end of the input or at something that is not a number, here the word apples. The call read_int(&v[n]) passes the address of an array element, so each number lands in its place in the array.

$ gcc -std=c89 -pedantic -Wall -Wextra -o read_ints read_ints.c
$ echo '12 -7 30 +5 100 apples 8' | ./read_ints
5 numbers, sum 140

The null pointer

C guarantees that no variable has the address 0. A pointer with the value 0 therefore points to nothing, and a function that returns a pointer can return 0 to report that it has found nothing. The constant 0 is the only integer that may be assigned to a pointer or compared with it.

find.c
#include <stdio.h>

/* return a pointer to the first x in v, or 0 if there is none */
int *find(v, n, x)
int v[];
int n, x;
{
    int i;

    for (i = 0; i < n; i++)
        if (v[i] == x)
            return &v[i];
    return 0;
}

int main()
{
    static int seats[] = { 4, 0, 2, 0, 6 };
    int *p;
    int i;

    p = find(seats, 5, 0);      /* the first empty row */
    if (p != 0)
        *p = 3;
    p = find(seats, 5, 9);
    if (p == 0)
        printf("no row with 9 seats\n");

    for (i = 0; i < 5; i++)
        printf("%d ", seats[i]);
    printf("\n");
    return 0;
}

find returns a pointer to int; the * in front of the function name in its definition says so. The caller uses the pointer to change the element it found, and it tests for 0 before using it. Indirection through a null pointer is an error that usually crashes the program. A function that returns a pointer and is used before its definition must be declared, for example int *find();, as the functions article explains for other non-int results.

$ gcc -std=c89 -pedantic -Wall -Wextra -o find find.c
$ ./find
no row with 9 seats
4 3 2 0 6 

Printing addresses

An address is a number, and a pointer can be cast to long and printed with %ld. Pointers have a size, like every other variable.

addresses.c
#include <stdio.h>

int total;

int main()
{
    int x;
    long big;
    int *p;

    p = &x;
    printf("size of a pointer: %d\n", (int) sizeof p);
    printf("&total = %ld\n", (long) &total);
    printf("&x     = %ld\n", (long) p);
    printf("&big   = %ld\n", (long) &big);
    return 0;
}

On x86-64 a pointer has eight bytes. The external variable total lies in the program's data area at a low address; the automatic variables lie on the stack, near the top of a 47-bit address space. The stack addresses change from run to run, because Linux places the stack at a random address to make attacks harder.

$ gcc -std=c89 -pedantic -Wall -Wextra -o addresses addresses.c
$ ./addresses
size of a pointer: 8
&total = 4210740
&x     = 140728848551316
&big   = 140728848551304

On the PDP-11 a pointer has two bytes, the same as an int, and a program has 64 KB of address space. The addresses are small numbers, and the stack starts at the top of the 16-bit space and grows down.

$ cc addresses.c
$ a.out
size of a pointer: 2
&total = 2584
&x     = 65466
&big   = 65462

Pointers and integers

On the PDP-11 a pointer and an int are both 16 bits, and the compiler converts between them without complaint. Programs of the time often kept addresses in int variables. The same code is wrong on a machine where a pointer is bigger than an int.

ptr_int.c
#include <stdio.h>

int main()
{
    int x, i;
    int *p, *q;

    x = 42;
    p = &x;
    i = p;          /* address kept in an int */
    q = i;          /* and turned back into a pointer */
    printf("same pointer: %d\n", q == p);
    printf("*q = %d\n", *q);
    return 0;
}

GCC warns about both assignments: they convert between a pointer and an integer without a cast. The program still compiles. The 64-bit address does not fit into the 32-bit int, so its upper half is lost; the pointer made back from i points to an address where nothing is mapped, and the program crashes on *q.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ptr_int ptr_int.c
ptr_int.c: In function ‘main’:
ptr_int.c:10:7: warning: assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast [-Wint-conversion]
   10 |     i = p;          /* address kept in an int */
      |       ^
ptr_int.c:11:7: warning: assignment to ‘int *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
   11 |     q = i;          /* and turned back into a pointer */
      |       ^
$ ./ptr_int
same pointer: 0
Segmentation fault (core dumped)
$ echo $?
139

On the PDP-11 the address fits into the int, the pointer comes back unchanged, and the program prints 42. Such code had to be fixed when C moved to machines with 32-bit and later 64-bit addresses.

$ cc ptr_int.c
$ a.out
same pointer: 1
*q = 42
$ echo $?
0

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Options to Request or Suppress Warnings

In this article we have covered pointers in K&R C: the address and indirection operators, pointer expressions, pointer arguments, returning values through pointers, the null pointer, the size of pointers, and pointers kept in integers. The next article, K&R C pointers and arrays, adds pointer arithmetic. Modern C pointers are covered in C pointers.

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.