简体   繁体   English

用用户输入元素声明数组

[英]Declaring arrays with user input elements

In C, when I declare an array of n elements a[n] , and n is input by the user, it shouldn't work, because the array space will change from static memory to dynamic memory. 在C语言中,当我声明一个由n元素a[n]组成的数组并且n由用户输入时,它不起作用,因为数组空间将从静态内存变为动态内存。

But it works! 但这有效! Why ? 为什么呢

Has the standard been updated or something? 标准是否已更新?

But it works! 但这有效! Why ? 为什么呢

Because C99 introduced variable length arrays . 因为C99引入了可变长度数组 and you can declare dynamic arrays. 您可以声明动态数组。

6.7.6.2 Array declarators: 6.7.6.2数组声明符:

If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; 如果大小是整数常量表达式,并且元素类型具有已知的常量大小,则数组类型不是可变长度数组类型; otherwise, the array type is a variable length array type. 否则,数组类型为可变长度数组类型。

Variable length arrays ( VLA ) are a C99 feature, so the compiler you are using supports VLA or is supporting it outside of C99 mode as an extension, such as gcc and clang . 可变长度数组VLA )是C99的一项功能,因此您使用的编译器支持VLA或在C99模式之外将其作为扩展名(例如gccclang)来支持

the C++ standard on the other hand does not support VLAs but many compilers including the ones I listed above support VLA in C++ as an extension. 另一方面, C ++标准不支持VLA,但包括我上面列出的那些在内的许多编译器都支持C ++中的VLA作为扩展。

We can see they were added in C99 by going to the draft C99 standard in the Foreword section it says: 我们可以通过在Foreword部分中提到的C99标准草案中看到它们已添加到C99中

[...]Major changes from the previous edition include: [...]与上一版相比的主要变化包括:

and includes the following bullet: 并包括以下项目符号:

— variable length arrays —可变长度数组

The C99 standard allows for variable-length arrays, which is exactly the behaviour that your are describing. C99标准允许使用可变长度数组,这正是您所描述的行为。

Edit: C99 is not universally supported (at least by default). 编辑:不普遍支持C99(至少默认情况下)。 However, many compilers (such as GCC) have incorporated a subset of the C99 standard into their default compilation settings. 但是,许多编译器(例如GCC)已将C99标准的子集合并到其默认编译设置中。

If you want to disable these features, you can do so in GCC by setting -ansi -pedantic in your compilation settings. 如果要禁用这些功能,可以在GCC中通过在编译设置中设置-ansi -pedantic禁用 This ensures that anything not supported in ANSI C will generate errors. 这样可以确保ANSI C中不支持的所有内容都将产生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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