C Academy · Lesson

Allocating an Array

Reserve heap memory.

Lesson 1 of 413 steps

Allocating an Array is a free C Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, and your progress syncs across the web and the CoddyKit app. The C Academy course includes 4 lessons in total.

Why Dynamic Arrays?

A normal array has a fixed size set at compile time. But often you don't know how many elements you need until the program runs.

Dynamic arrays solve this: you ask the operating system for a block of memory at runtime using malloc, and you decide the size with a variable.

Meet malloc

malloc (memory allocate) lives in <stdlib.h>. You pass it a number of bytes and it returns a pointer to that block, or NULL if it fails.

The memory comes from the heap and stays alive until you free it.

int *p = malloc(10 * sizeof(int));

Sizing with sizeof

Never hardcode byte counts. Use sizeof so your code stays correct across platforms.

To allocate space for n integers, multiply n by sizeof(int). A common idiom is n * sizeof(*p), which uses the pointer's own type.

int *p = malloc(n * sizeof(*p));

Always Check for NULL

If the system is out of memory, malloc returns NULL. Dereferencing a NULL pointer crashes your program.

Check the result before using it. This single habit prevents many hard-to-debug failures.

int *p = malloc(n * sizeof(*p));
if (p == NULL) {
    fprintf(stderr, "out of memory\n");
    return 1;
}

A Complete Allocation

Here is a full program that allocates room for 5 integers, fills them, and prints them.

Notice the symmetry: malloc at the start, free at the end.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 5;
    int *a = malloc(n * sizeof(*a));
    if (!a) return 1;
    for (int i = 0; i < n; i++) a[i] = i * i;
    for (int i = 0; i < n; i++) printf("%d\n", a[i]);
    free(a);
    return 0;
}

malloc Does Not Zero

Memory from malloc is uninitialized: it holds whatever garbage was there before.

Reading it before writing gives unpredictable values. Always assign every element before you read it.

int *a = malloc(3 * sizeof(*a));
/* a[0], a[1], a[2] hold garbage here */
a[0] = 10;

calloc Zeroes for You

calloc(count, size) allocates room for count elements of size bytes and sets every byte to zero.

Use it when you want a clean, zero-filled array. It also guards against overflow in the multiplication.

int *a = calloc(5, sizeof(*a));
/* every element is now 0 */

calloc in Action

This program uses calloc and confirms the array starts at zero before we change it.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 4;
    int *a = calloc(n, sizeof(*a));
    if (!a) return 1;
    for (int i = 0; i < n; i++) printf("%d\n", a[i]);
    free(a);
    return 0;
}

Indexing the Block

A pointer to a heap block behaves just like an array name. You can use a[i] to read and write any element from 0 to n-1.

Under the hood a[i] is the same as *(a + i).

int *a = malloc(3 * sizeof(*a));
a[0] = 1;
*(a + 1) = 2;   /* same as a[1] = 2 */
a[2] = 3;

Watch the Bounds

If you allocate n elements, valid indexes are 0 through n-1. Writing to a[n] is undefined behavior.

C does not check bounds for you, so an off-by-one bug can corrupt memory silently.

int *a = malloc(3 * sizeof(*a));
a[2] = 99;   /* OK, last valid index */
/* a[3] = 0;  BUG: out of bounds */

Reading the Size at Runtime

The real power: the size can come from input, a file, or a calculation. The same code allocates 2 or 2 million elements.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 6;            /* could be scanf'd */
    long *a = malloc(n * sizeof(*a));
    if (!a) return 1;
    long sum = 0;
    for (int i = 0; i < n; i++) { a[i] = i + 1; sum += a[i]; }
    printf("%ld\n", sum);
    free(a);
    return 0;
}

Quick Check

Test your understanding of allocation.

Recap

You allocate a dynamic array with malloc(n * sizeof(*p)) or zero-filled with calloc(n, sizeof(*p)).

Always check for NULL, remember malloc leaves garbage, index from 0 to n-1, and pair every allocation with a free. Next you'll learn to resize a block while keeping its data.

Free to start

Learn C with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
39
Lessons
144

Frequently Asked Questions

Is the “Allocating an Array” lesson free?

Yes — the full text of “Allocating an Array” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO. The C Academy course includes 4 lessons in total.

What will I learn in “Allocating an Array”?

Reserve heap memory. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C Academy?

No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Allocating an Array” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C Academy lesson?

Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Allocating an Array
  2. Growing with realloc
  3. A Reusable Vector Type
  4. Freeing and Avoiding Leaks
← Back to C Academy