pointers-memory · intermediate · ~15 min

Distance between pointers

Pointer subtraction yields an element count, not a byte count.

Challenge

Measure how far apart two pointers into the same array are, counted in elements. Subtracting pointers gives an element count, not a byte count.

Task

Implement int ptr_distance(const int *a, const int *b) that returns b - a: how many int elements b is past a. No main — the grader calls it.

Input

a and b — two pointers into the same int array.

Output

Returns the signed element offset b - a (negative if b precedes a).

Example

int a[] = {0,1,2,3,4};
ptr_distance(&a[0], &a[3])   ->   3
ptr_distance(&a[2], &a[2])   ->   0
ptr_distance(&a[4], &a[1])   ->   -3

Edge cases

  • Same pointer: returns 0.
  • b before a: result is negative.

Input format

a and b — two pointers into the same int array.

Output format

The signed element distance b - a.

Starter code

int ptr_distance(const int *a, const int *b) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.