关于c99编译的问题

我在看一些老师讲的c的课件,在声明数组长度的时候使用const常量来指定数组长度。

const int length=10;
int arr[length]={.....};

为什么我在本地编译通不过?据说是跟编译器支持次c99有关系。

./test2.c:10:2: error: variable-sized object may not be initialized
int arr[num]={2};
^

我在编译的时候加上了 -std=c99也还是不行

阅读 4.9k
3 个回答

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );

原文

当然C99支持常量定义动态长度的数组,但是根据你的代码,你虽然有定义常量,但是你定义的常量不是编译时常量,编译器在编译时并不会得到长度,所以其实你的常量并没有起效,实在要这样写,可以把声明和定义分开:

const int length = 3;
int arr[length]; // 声明,编译时会取得常量
arr[0] = 1; // 定义
arr[1] = 1;
arr[2] = 1;
arr[3] = 1; // 越界

当然,如果你对内存操作熟悉,上述老外的答案也是个不错的写法。

const int length=10;int arr[length];

这样的写法是没问题的. 问题在于不能用变量声明数组大小的同时初始化.

初始化这样的数组还是需要使用循环的;

for(int i = 0; i < length ; i++){
    arr[i] = ?????;
}
    

一般不用变量定义数组个数,可以用宏来代替

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进