pointers-memory · intermediate · ~15 min

Zero-initialised allocation

Use calloc for zeroed memory.

Challenge

Allocate a zero-initialised int array using calloc, which both reserves and zeroes the memory in one call.

Task

Implement int *zeros(int n) that returns an array of n ints allocated with calloc, so every element is 0. No main — the grader calls it and frees the result.

Input

n — the number of ints to allocate.

Output

Returns a calloc-ed int* of length n, all elements 0. The caller frees it.

Example

zeros(4)   ->   {0, 0, 0, 0}

Rules

  • Use calloc (not malloc + manual zeroing). The caller frees the result.

Input format

n — the number of ints to allocate.

Output format

A calloc-ed int array of length n, all zero (caller frees).

Constraints

Use calloc to allocate and zero in one step; the caller frees it.

Starter code

#include <stdlib.h>

int *zeros(int n) {
    /* TODO */
    return NULL;
}

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