pointers-memory · beginner · ~5 min
Understand that a[n] is *(a + n).
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).
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.
a — a pointer to the first element of an int array. n — a 0-indexed position guaranteed to be in range.
Returns the int at offset n.
int a[] = {10, 20, 30, 40};
nth(a, 0) -> 10
nth(a, 2) -> 30
Drill: practice one contract before combining it with other skills.
a — a pointer to the first element of an int array. n — a 0-indexed position guaranteed to be in range.
Returns the int at offset n.
a points into a live int array; n is nonnegative and in range. Read only. NULL and invalid indices are outside this contract.
int nth(const int *a, int n) {
/* TODO: use *(a + n) */
return 0;
}
Multiplying the offset by sizeof(int) even though pointer arithmetic already scales by element size.
First and last valid positions, one-element arrays, negatives stored in the array.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.