Question

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;

}
Was it helpful?

Solution

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:

typedef unsigned long long uint64; // just for convenience
uint64* Fibonacci = (uint64*)malloc(sizeof(uint64)*numFibs);
// {code here}
// then at the end:    
free(Fibonacci);
return 0;

OTHER TIPS

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.

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.

#define kMaxFibs 75
...
if ( numFibs < 1 || numFibs > kMaxFibs){
...
unsigned long long int Fibonacci[kMaxFibs];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top