关于c99编译的问题

发布于 2022-09-05 01:16:52 字数 281 浏览 21 评论 0

我在看一些老师讲的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也还是不行

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绝情姑娘 2022-09-12 01:17:10
const int length=10;int arr[length];

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

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

for(int i = 0; i < length ; i++){
    arr[i] = ?????;
}
    
绮烟 2022-09-12 01:17:10

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

瀟灑尐姊 2022-09-12 01:17:09

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; // 越界

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文