Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c99 - Dynamic array allocation on stack in C

I just did a experiment yesterday, and find something confusing:

#include <stdio.h>

int main()
{
    int j;
    scanf("%d",&j);
    const int i = j;
    int arr[i];
    return 0;
}

The number j is read from keyboard and it’s used to allocate the array arr on the stack.

The compiler does not even know the size of the array at compile time (initializes j to 0?), but there is no compilation error. How is it possible?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Variable length arrays were added to C99. It's described in the C99 rationale:

6.7.5.2 Array declarators

C99 adds a new array type called a variable length array type. The inability to declare arrays whose size is known only at execution time was often cited as a primary deterrent to using C as a numerical computing language. Adoption of some standard notion of execution time arrays was considered crucial for C’s acceptance in the numerical computing world.

The number of elements specified in the declaration of a variable length array type is a runtime expression. Before C99, this size expression was required to be an integer constant expression.

There is no "dynamic array allocation on the stack". The array size has to be specified at the declaration.

Some compilers, like GCC allow them as an extension in C90 (in GCC, this is equivalent to ansi and C89) mode and C++. In these cases, you will get a warning (-Wpedantic) or an error (-Werror or -pedantic-errors). Consult the documentation for your compiler.

Per @Deduplicator's comment, you seem to have a misconception. Variable length arrays cannot be declared static.

§ 6.7.6.2

10 EXAMPLE 4 All declarations of variably modified (VM) types have to be at either block scope or function prototype scope. Array objects declared with the _Thread_local, static, or extern storage-class specifier cannot have a variable length array (VLA) type. However, an object declared with the static storage-class specifier can have a VM type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type have to be ordinary identifiers and cannot, therefore, be members ostructures or unions.

This means that static storage and automatic storage are mutually exclusive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...