Skip to study material
← Question index

QUESTION 02 · Pointer Basics

Define a pointer and explain the address and dereference operators.

5 marks

Answer in brief

A pointer variable stores a pointer value. A valid object pointer can be used to access an object indirectly.

Declaration

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

Address operator

&number produces the address of number. The declaration stores that address in p. The star in int *p declares a pointer type; it does not read the object at that point. The pointer and the pointed-to integer are separate objects.

Dereference operator

In an expression, *p accesses the integer to which p points. Reading *p initially gives 10. Assigning *p = 25 changes number itself to 25. It does not change which object p identifies.

Example trace

The program first prints the value through *p. It then assigns through *p and prints number. The second output is 25, demonstrating that direct access through number and indirect access through p reach the same object.

Important points

  1. Initialise a pointer before using its stored value.
  2. Dereference only a pointer that identifies a suitable live object.
  3. Do not dereference NULL, a one-past-end position or an invalid pointer.
  4. Use %p with an object pointer converted to void * when displaying an address; the displayed form depends on the implementation.

Complexity

A direct pointer dereference and assignment to a fixed-size object take O(1) work in the usual model. A pointer does not automatically allocate the object it is expected to identify.

Diagram or flowchart

CodeBhavya illustration of pointer object.
Define a pointer and explain the address and dereference operators. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    int number = 10;
    int *p = &number;
    printf("Before = %d\n", *p);
    *p = 25;
    printf("After = %d\n", number);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Before = 10
After = 25

Related exam questions

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

  • March/April 2023 · Q1(c) · 2 marks

    How is a pointer variable declared?

    Paper P02 · page 1
  • March/April 2023 · Q1(d) · 1 marks

    Define a pointer.

    Paper P05 · page 1

View this category in the exam question bank →