Skip to study material
← Question index

QUESTION 14 · Pointers and Arrays

Explain valid pointer arithmetic and pointer subtraction.

5 marks

Answer in brief

Pointer arithmetic moves between elements of the same array. Its step is measured in elements of the pointed-to type.

Addition and subtraction

If p identifies a[i], p + k can identify a[i + k] when the result is within that array or one past it. p - k moves backwards under the same restriction. p++ updates the pointer to the next element; (*p)++ instead increments the pointed-to value, when that value is writable and the operation is valid.

Pointer difference

Subtracting two suitable pointers into the same array gives their distance in elements, of type ptrdiff_t. The sample sets first to a[0] and last to a[3], so last - first gives 3. Use %td to print ptrdiff_t. The difference must be representable in that type.

One-past-end rule

a + n can be formed for an array of n elements, but it must not be dereferenced. This permits a loop that stops when p equals the end pointer. Do not continue arithmetic beyond that position, even if an unrelated object happens to follow in memory.

Invalid operations

  1. Adding two pointers is not a defined pointer operation.
  2. Do not subtract pointers into unrelated arrays.
  3. Do not assume ordering comparisons between unrelated objects follow their displayed addresses.
  4. Standard C does not support arithmetic on function pointers or void *.

Complexity

A valid pointer step or difference is O(1) in the usual machine model. A loop that advances once per element still takes O(n) time and O(1) auxiliary space. The rules are about array membership, not merely whether an address appears numerically nearby.

Diagram or flowchart

CodeBhavya illustration of pointer step.
Explain valid pointer arithmetic and pointer subtraction. · Download diagram

C program and output

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

int main(void)
{
    int a[4] = {10, 20, 30, 40};
    int *first = a, *last = a + 3;
    printf("Next = %d\n", *(first + 1));
    printf("Distance = %td\n", last - first);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Next = 20
Distance = 3

Related exam questions

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

  • March/April 2023 · Q4(b) · 4 marks

    Write about pointer arithmetic operations.

    Paper P05 · page 1

View this category in the exam question bank →