使用可变长度数组生成斐波那契数代码编译器错误
下面的代码在vs2010(Win32控制台应用程序模板)中编译错误。我该如何解决它。
unsigned long long int Fibonacci[numFibs]; // error occurred here
错误 C2057: 预期的常量表达式
错误 C2466: 无法分配常量大小为 0 的数组
错误 C2133: 'Fibonacci' : 未知大小
附加完整代码(这是《c -3E》书中的编程示例代码。否任何修改)
int main()
{
int i, numFibs;
printf("How may Fibonacci numbers do you want (between 1 to 75)? ");
scanf("%i", &numFibs);
if ( numFibs < 1 || numFibs > 75){
printf("Bad number, sorry!\n");
return 1;
}
unsigned long long int Fibonacci[numFibs];
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < numFibs; ++i)
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < numFibs; ++i)
printf("%11u",Fibonacci[i]);
printf("\n");
return 0;
}
Compile error in vs2010(Win32 Console Application Template) for the code below. How can I fix it.
unsigned long long int Fibonacci[numFibs]; // error occurred here
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'Fibonacci' : unknown size
Complete code attached(It's a sample code from programming In c -3E book. No any modify)
int main()
{
int i, numFibs;
printf("How may Fibonacci numbers do you want (between 1 to 75)? ");
scanf("%i", &numFibs);
if ( numFibs < 1 || numFibs > 75){
printf("Bad number, sorry!\n");
return 1;
}
unsigned long long int Fibonacci[numFibs];
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < numFibs; ++i)
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < numFibs; ++i)
printf("%11u",Fibonacci[i]);
printf("\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
VS2010默认是C++编译器,C++不支持变长数组。您可以更改项目以将代码编译为C代码,但VS2010仍然不真正支持C99。
我建议您使用
gcc
来编写 C 代码,它更加一致。VS2010 is a C++ compiler by default, and C++ does not support variable length arrays. You can change your project to compile code as C code, but VS2010 still doesn't really support C99.
I would recommend you use
gcc
for C code, it's much more conformant.您使用哪个编译器?你是编译为 C 还是 C++ ?
自 C99 起,可变长度数组在 C 中是合法的,但如果您使用的是较旧的编译器(或编译为 C++)它们不会工作。
作为解决方法,您可以切换到使用动态分配:
Which compiler are you using? And are you compiling as C or C++?
Variable-length arrays are legal in C since C99, but if you're using an older compiler (or compiling as C++) they won't work.
As a workaround, you can switch to using dynamic allocation:
您不能拥有可变长度的数组。使用动态分配返回指针(malloc)
You cannot have an array of variable length. Use dynamic allocation returning pointer (malloc)
动态分配数组或使用常量数组大小。
Either dynamically allocate the array or use a constant array size.