The size of the C array given by the variable

Today I found some code that confused me. He did something like this:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[x];

    foo[0] = 33;
    printf("%d\n", foo[0]);
    return 0;
}

My question is: why does this work?

The array foois on the stack, so how can it be deployed to x?

I would expect something like this:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[] = malloc(sizeof(int)*x);

    foo[0] = 33;
    printf("%d\n", foo[0]);
    free(foo);
    return 0;
}

Not that it's prettier or something, but, I'm just curious.

+4
source share
2 answers

Excerpt

int foo[x];

says an advantage in something called a VLA ( Variable length array ). It was introduced in the standard C99, only to make an optional function in C11.

Thus, we can create an array data structure whose length is given (set) at runtime.

, , gcc VLA ( ).

+9

foo , x?

gcc :

subq    %rax, %rsp

+2

All Articles