pointers-memory · intermediate · ~5 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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

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

Constraints

Both pointers belong to one live int array or its one-past position. The signed difference fits int. Do not subtract unrelated pointers.

Starter code

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

Common mistakes

Returning byte distance or reversing the subtraction.

Edge cases to handle

Equal pointers give zero; reverse order gives a negative distance; include a one-past boundary.

Up next

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