是否可以创建具有可变数量元素的数组?
Is creating array with a variable number of elements possible?
每当我需要创建一个数组,其中包含许多直到执行时才知道的元素时,我都会这样做。
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int myArray[n];
for(i = 0; i < n; i++)
myArray[i] = 0;
然而,3 位拥有计算机科学博士学位的人告诉我不要这样做,因为 "it's not guaranteed to work on every compiler",并且数组中元素的数量必须在编译时已知。所以他们就是这样做的。
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 支持的情况下。否则,您充其量只能满足于指针和内存分配函数。
如果您想要符合 C89 且不使用太多内存的东西,还有第三种选择,即动态分配内存:
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int *myArray = malloc(sizeof(int)*n); // allocate space for n ints
if (myArray == NULL) {
perror("malloc failed");
exit(1);
}
for(i = 0; i < n; i++)
myArray[i] = 0;
请务必在分配的内存上调用 free
。
每当我需要创建一个数组,其中包含许多直到执行时才知道的元素时,我都会这样做。
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int myArray[n];
for(i = 0; i < n; i++)
myArray[i] = 0;
然而,3 位拥有计算机科学博士学位的人告诉我不要这样做,因为 "it's not guaranteed to work on every compiler",并且数组中元素的数量必须在编译时已知。所以他们就是这样做的。
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 支持的情况下。否则,您充其量只能满足于指针和内存分配函数。
如果您想要符合 C89 且不使用太多内存的东西,还有第三种选择,即动态分配内存:
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int *myArray = malloc(sizeof(int)*n); // allocate space for n ints
if (myArray == NULL) {
perror("malloc failed");
exit(1);
}
for(i = 0; i < n; i++)
myArray[i] = 0;
请务必在分配的内存上调用 free
。