Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

C array size given by variable

I found some code today that confused me. It did something like this:

#include <stdio.h>

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

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

My Question is why does this work?

The array foo is on the stack so how could it be expanded by x?

I would have expected some thing 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
", foo[0]);
    free(foo);
    return 0;
}

Not that it is prettier or something but, I just wonder.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The snippet

int foo[x];

is talking advantage of something called VLA (Variable length array) feature. It was introduced in C99 standard, just to be made an optional feature in C11.

This way, we can create an array data structure, whose length is given (supplied) at run-time.

Point to note, though created at runtime, gcc allocates the VLAs on stack memory (unlike the dynamic memory allocation from heap memory).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...