pointers-memory · intermediate · ~15 min

Allocate a range

Allocate, initialise, and return heap memory.

Challenge

Allocate a heap array, fill it with a counting sequence, and return it for the caller to use and free.

Task

Implement int *make_range(int n) that mallocs an array of n ints, fills it with 0, 1, ..., n-1, and returns the pointer. No main — the grader calls it and frees the result.

Input

n — the number of ints to allocate (at least 1 in the tests).

Output

Returns a malloc-ed int* of length n holding 0..n-1. The caller owns and frees it.

Example

make_range(5)   ->   {0, 1, 2, 3, 4}
make_range(1)   ->   {0}

Rules

  • The returned block is heap-allocated; the caller is responsible for free.

Input format

n — the number of ints to allocate and fill.

Output format

A malloc-ed int array of length n holding 0..n-1 (caller frees).

Constraints

Allocate with malloc; the caller frees the result.

Starter code

#include <stdlib.h>

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

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