Skip to study material
← Question index

QUESTION 08 · Pointers and Functions

Explain pointers to pointers with an example.

5 marks

Answer in brief

A pointer to a pointer identifies another pointer object. It is useful when a function must update a caller’s pointer value.

Basic declarations

int number = 10;
int *p = &number;
int **pp = &p;

Two access levels

pp identifies p. Therefore *pp refers to p itself, and **pp reaches number. These levels must be interpreted in order. A declaration of int ** does not automatically create either a pointer target or an int target; all objects must already exist or be allocated appropriately.

Function example

redirect receives &p and &second. Its parameter slot identifies main’s pointer p. Assigning *slot = target changes p to identify second. After the call, *p reads 20. The function has changed which integer p points at, rather than assigning 20 into the first integer.

Why a single pointer parameter is insufficient

If the function received only a copy of p as int *local, assigning local = &second would change only local. Passing the address of p allows the function to reach and assign main’s actual pointer object. The argument is still passed by value: the copied value is now a pointer to that pointer object.

Precautions and complexity

The slot must identify a live, writable int * object. A null check alone does not prove a non-null pointer is valid. The supplied target must also remain alive while it is used. The sample uses two local ints and one pointer during the same main call, so all lifetimes are suitable. Its fixed assignments use O(1) time and auxiliary space.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void redirect(int **slot, int *target)
{
    if (slot != NULL) { *slot = target; }
}

int main(void)
{
    int first = 10, second = 20;
    int *p = &first;
    redirect(&p, &second);
    printf("Selected = %d\n", *p);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Selected = 20

Related exam questions

Related questions in the pointer function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September 2023 · Q9(b) · 4 marks

    Explain passing pointers to a function, with examples.

    Paper P09 · page 2

View this category in the exam question bank →