C Workshop · Allocate an Array
Lesson C

Allocate an Array

malloc can reserve many ints: malloc(n * sizeof(int)). Then use p[i] like an array.

What it is

malloc can rent a whole row: three ints in one block. You use p[i] like an array, add them up, print 6, then free the block once — not once per index.

Approach

  1. p = malloc(3 * sizeof(int));
  2. Fill p[0], p[1], p[2].
  3. Print the sum, then free(p).

Where this is used in the real world

Diagram

1

3 ints

heap

2

1 2 3

fill

3

sum

6

4

free

one block

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <stdlib.h>
3int main(void) {
4    int *p = malloc(3 * sizeof(int));
5    if (!p) return 1;
6    p[0] = 1; p[1] = 2; p[2] = 3;
7    printf("%d\n", p[0] + p[1] + p[2]);
8    free(p);
9    return 0;
10}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. 1+2+3 prints:

Sum.

2. malloc(3 * sizeof(int)) is:

One block.

3. free(p) frees:

One free.

4. p[i] works because:

Array indexing on a pointer.

5. Stack int a[3] vs this malloc:

Lifetime and size.