pointers-memory · beginner · ~5 min

Nth element via pointer arithmetic

Understand that a[n] is *(a + n).

Challenge

Fetch the n-th element of an array using pointer arithmetic instead of the indexing operator, to see that a[n] is just *(a + n).

Task

Implement int nth(const int *a, int n) that returns the element at position n using *(a + n) (not a[n]). No main — the grader calls it.

Input

a — a pointer to the first element of an int array. n — a 0-indexed position guaranteed to be in range.

Output

Returns the int at offset n.

Example

int a[] = {10, 20, 30, 40};
nth(a, 0)   ->   10
nth(a, 2)   ->   30

Why this matters

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

Input format

a — a pointer to the first element of an int array. n — a 0-indexed position guaranteed to be in range.

Output format

Returns the int at offset n.

Constraints

a points into a live int array; n is nonnegative and in range. Read only. NULL and invalid indices are outside this contract.

Starter code

int nth(const int *a, int n) {
    /* TODO: use *(a + n) */
    return 0;
}

Common mistakes

Multiplying the offset by sizeof(int) even though pointer arithmetic already scales by element size.

Edge cases to handle

First and last valid positions, one-element arrays, negatives stored in the array.

Up next

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