- 一直深信,数组长度必须是一个编译时可确定的常数,最近才发现自己真的是out了,自己真的是老了。
C99标准已经支持变长数组,换言之,数组的长度可以在运行时确定,没有任何问题。但是有个问题,就是数组只能够声明,不能初始化,因为编译器并不知道数组的长度,无法初始化。请看下面的例子:第一个例子,表明数组长度可以直到运行时才确定。第二个例子表明,运行时才能确定长度的数组,不能初始化。
-
-
#include<stdio.h> int test_array() { int a ; printf("please input the array's length \n"); scanf("%d",&a); int b[a] ; printf("We can define a array with len we input\n"); b[a-1] = 3; printf("the last element of array is %d\n",b[a-1]); return 0; } int main() { test_array(); return 0; }
int test_array() { int a ; printf("please input the array's length \n"); scanf("%d",&a); int b[a] = {0,}; printf("We can define a array with len we input\n"); b[a-1] = 3; printf("the last element of array is %d\n",b[a-1]); return 0; } int main() { test_array(); return 0; }
VC++编译均不通过,GCC编译器第一段程序通过,第二段不通过 -
-
关于数组长度不需要编译时确定
最新推荐文章于 2022-11-04 17:01:56 发布