pointers-memory · beginner · ~6 min

Fill an array

Write through an array pointer.

Challenge

Set every element of an array to the same value, writing through the array pointer.

Task

Implement void fill(int *a, int n, int v) that sets the first n elements of a to v. No main — the grader calls it.

Input

a — pointer to an int array. n — number of elements to set (may be 0). v — the value to write.

Output

No return value. The first n elements of a become v.

Example

int a[4] = {1,2,3,4}; fill(a, 4, 9)   ->   a == {9,9,9,9}
int b[3] = {5,5,5};   fill(b, 0, 0)   ->   b unchanged

Edge cases

  • n == 0: writes nothing.

Why this matters

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

Input format

a — pointer to an int array. n — number of elements to set (may be 0). v — the value to write.

Output format

No return value. The first n elements of a become v.

Constraints

n is nonnegative; a points to live writable storage for at least n ints. When n=0 no access occurs. No allocation; preserve other elements.

Starter code

void fill(int *a, int n, int v) {
    /* TODO */
}

Common mistakes

Using i <= n or filling the whole backing array instead of the requested prefix.

Edge cases to handle

Empty range, one element, zero/negative fill values, and a subrange with untouched neighbors.

Up next

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