pointers-memory · intermediate · ~5 min
Pointer subtraction yields an element count, not a byte count.
Measure how far apart two pointers into the same array are, counted in elements. Subtracting pointers gives an element count, not a byte count.
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.
a and b — two pointers into the same int array.
Returns the signed element offset b - a (negative if b precedes a).
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
b before a: result is negative.Drill: practice one contract before combining it with other skills.
a and b — two pointers into the same int array.
Returns the signed element offset b - a (negative if b precedes a).
Both pointers belong to one live int array or its one-past position. The signed difference fits int. Do not subtract unrelated pointers.
int ptr_distance(const int *a, const int *b) {
/* TODO */
return 0;
}
Returning byte distance or reversing the subtraction.
Equal pointers give zero; reverse order gives a negative distance; include a one-past boundary.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.