C语言 错误 C2057:预期的常量表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7303740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error C2057: expected constant expression
提问by Ava
if(stat("seek.pc.db", &files) ==0 )
sizes=files.st_size;
sizes=sizes/sizeof(int);
int s[sizes];
I am compiling this in Visual Studio 2008 and I am getting the following error: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0.
我正在 Visual Studio 2008 中编译它,但出现以下错误:错误 C2057:预期的常量表达式错误 C2466:无法分配常量大小为 0 的数组。
I tried using vector s[sizes] but of no avail. What am I doing wrong?
我尝试使用向量 s[sizes] 但无济于事。我究竟做错了什么?
Thanks!
谢谢!
回答by hmakholm left over Monica
The sizes of array variables in C must be known at compile time. If you know it only at run time you will have to mallocsome memory yourself instead.
C 中数组变量的大小必须在编译时知道。如果你只在运行时知道它,你将不得不malloc自己拥有一些记忆。
回答by Mahesh
Size of an array must be a compile time constant. However, C99 supports variable length arrays. So instead for your code to work on your environment, if the size of the array is known at run-time then -
数组的大小必须是编译时常量。但是,C99 支持可变长度数组。因此,如果在运行时知道数组的大小,那么您的代码可以在您的环境中工作,那么 -
int *s = malloc(sizes);
// ....
free s;
Regarding the error message:
关于错误信息:
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.

