pointers-memory · beginner · ~15 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

Input format

a — pointer to an int array; n — an in-range 0-based index.

Output format

The int element at position n.

Constraints

Use pointer arithmetic *(a + n), not the [] operator.

Starter code

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

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