c - 是否可以创建具有可变数量元素的数组?

标签 c arrays variable-length-array

每当我需要创建一个包含许多直到执行时才知道的元素的数组时,我都会这样做。

int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int myArray[n];
for(i = 0; i < n; i++)
    myArray[i] = 0;

然而,3 位拥有计算机科学博士学位的人告诉我不要这样做,因为“不能保证它适用于每个编译器”,并且数组中元素的数量必须在编译时已知-时间。所以他们这样做。

int myArray[1000];
int n, i;
printf("Number of elements: ");
scanf("%d, &n);
//we must stop at the n element
for(i = 0; i < n; i++)
    myArray[i] = 0;

我应该使用哪一个?什么时候不能保证工作?仅仅是内存浪费还是需要维护遗留?

最佳答案

"it's not guaranteed to work on every compiler"

是的,基本上是正确的。

第一种方法,VLA, variable length array , 是 C99 标准的一部分。然而,

  • C11 中,它已成为可选的。您最好不要依赖该功能。
  • C89 没有将其作为标准的端口。但是,gcc 扩展可以支持它们。

引用 C11,章节 §6.7.6.2/p5

[....] 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 are a conditional feature that implementations need not support; see 6.10.8.3.)

作为替代方法,您始终可以使用指针和动态内存分配,如 malloc()和家人,如果您必须依赖运行时值。

综合起来,回答问题

Is creating array with a variable number of elements possible?

这是可能的,但只有在 VLA 支持的情况下。否则,您充其量只能满足于指针和内存分配函数。

关于c - 是否可以创建具有可变数量元素的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666081/

相关文章:

java - 如何仅打印字符串数组中的重复项一次

javascript - 减少大数组JS中对象中的数组

c - 变长数组指令是如何生成的?

C qsort 不对结构数组进行排序

c - fuse filesystem不能改变getattr函数中struct stat *stbuf的值?

c - 访问指针数组中的元素

c - C99 如何处理无法在运行时创建变长数组的情况?

c - C中动态分配的结构数组

c - 用getchar替换gets的用法

c - 需要检测任何可能的缓冲区溢出