C/C++ Arena

Step 2 of 10

Size decided at runtime

The first real payoff of malloc: the size can depend on data you only learn while the program runs, such as a count in the input. A stack array would need a guessed maximum; a heap array is exactly as big as needed.

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

int main(void) {
    int n;
    scanf("%d", &n);
    int *vals = malloc(n * sizeof *vals);
    if (vals == NULL) {
        return 1;
    }
    for (int i = 0; i < n; i++) {
        scanf("%d", &vals[i]);
    }
    int evens = 0;
    for (int i = 0; i < n; i++) {
        if (vals[i] % 2 == 0) {
            evens++;
        }
    }
    printf("%d of %d are even\n", evens, n);
    free(vals);
    return 0;
}
5
3 8 10 7 4
3 of 5 are even

sizeof *vals

n * sizeof *vals means "n times the size of whatever vals points at". It's the same as sizeof(int) here, but it stays correct if you later change the type of vals to long or double, because it follows the pointer's type automatically. Many style guides prefer it for that reason.

Two passes

Some questions need the data twice: "how many are above the average" needs the average first (one pass to sum), then a second pass to compare each value. That's why the values are stored in an array instead of being processed while reading.

Don't forget free

When main returns, the operating system reclaims all memory anyway, so a missing free at the very end of main does no visible harm. But the habit matters: the same code inside a function that runs thousands of times would leak memory each time. Free what you allocate, always.

Your turn: read n, then n numbers into a heap array. Print how many are above the average. Free the array at the end.

Input 4 / 2 4 6 8 (average 5) prints 2.

Previous: Stack vs heap Next: Return heap memory from a function