错误 C2057:预期常量表达式

12
if(stat("seek.pc.db", &files) ==0 )
     sizes=files.st_size;

sizes=sizes/sizeof(int);
int s[sizes];

我正在使用Visual Studio 2008进行编译,但是出现以下错误: error C2057: 期望常量表达式 error C2466: 无法分配大小为0的常量数组。

我尝试使用vector s[sizes],但没有成功。我做错了什么?

谢谢!


1
只是想通知一下,这是一个与编译器有关的问题,请尝试使用gcc(C99),您的代码将被编译。 - Levent Divilioglu
2个回答

11

C语言中的数组变量大小必须在编译时确定。如果只有在运行时才知道大小,你将需要手动使用 malloc 分配内存。


9
C99确实有可变长度数组(VLAs),但是微软的编译器不支持它们。(“无法分配大小为0的常量数组”错误可能只是编译器困惑了。) - Keith Thompson
我尝试通过 int *s=new int[sizes]; 分配内存。但是它给了我 System.AccessViolationException 错误。这是因为这个原因吗? - Ava
@Richa,这更像是 .net 而不是C。而 new int[size] 不是 C 语法,它是 C++ 语法。 - hmakholm left over Monica
抱歉,它只是C++,我已经解决了。我将文件存储在错误的位置。谢谢! - Ava
2
这是一个编译器相关的答案。GCC编译该语句:“unsigned char message [getLen(cipher)];”,但相同的代码不能通过MS VS编译。请查看: https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html - Levent Divilioglu

6

数组的大小必须是编译时常量。然而,C99支持可变长度数组。因此,如果数组的大小在运行时已知,则可以使您的代码在您的环境中正常工作,如下所示:

int *s = malloc(sizes);
// ....
free s;

关于错误信息:

int a[5];
   // ^ 5 is a constant expression

int b = 10;
int aa[b];
    // ^   b is a variable. So, it's value can differ at some other point.

const int size = 5;
int aaa[size];  // size is constant.

我可以在 const int size = 5; 中将大小初始化为变量吗? - Ava
@Richa - 你必须初始化一个常量变量。你不能对它进行任何形式的赋值操作。http://ideone.com/D4L5r - Mahesh
我试图通过 int *s=new int[sizes]; 分配内存。它给我返回了 System.AccessViolationException 错误。是因为这个吗? - Ava
@Richa - 请发布你正在做的代码。new 没有问题。可能是因为您访问了超出 0 到 sizes - 1 的索引。 - Mahesh
我已经解决了。我把文件存储在错误的位置。谢谢! - Ava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接