简体   繁体   中英

How do arrays with length defined by variables in C get stored in memory?

I have tried searching this out a lot. Static arrays are generally stored in a stack and their size is determined during compilation time. Ex:

int main()
{
    int n;
    scanf("%d", &n);
    int array[n];
    printf("%u", sizeof(array));
    return 0;
}

The size of array changes for different values of n. Hence, shouldn't the array here be stored in a heap as the size is determined at run-time? Have been confused about this. Please help. Thank You!

shouldn't the array here be stored in a heap as the size is determined at run-time?

It could , but it is not the only way to do it. C compiler is smart enough to defer the allocation of memory for this variable-length array in the automatic memory (commonly known as "the stack") to the point in code where the size of the array becomes known.

In order to make this possible, a related trick for sizeof needed to be created. Usually, sizeof is evaluated at compile-time; variable-length arrays, however, changed that, requiring the sizeof expressions on VLAs to be evaluated at runtime. Again, the compiler provides the "enabling technology" for that by storing the actual size of your VLA in a separate hidden location in memory.

See what standard says about this special case:

C11: 6.5.3.4 (p2):

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated ; otherwise, the operand is not evaluated and the result is an integer constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM