C array size given by variable

后端 未结 2 557
[愿得一人]
[愿得一人] 2020-12-02 02:23

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

#include 

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


        
相关标签:
2条回答
  • 2020-12-02 02:47

    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).

    0 讨论(0)
  • 2020-12-02 02:47

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

    gcc simply moves the stack pointer:

    subq    %rax, %rsp
    

    Link to full example with assembly output

    0 讨论(0)
提交回复
热议问题