1
votes

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;

}
4
Before you get too far in that book I recommend you browsing around to find all the differences between C89 and C99. Your book looks to be using C99. C89 is the most common "standard C" out there. C99 changes a few things, probably for the worst, but you're better off knowing what the differences are and know how to spot different standards. - BobbyShaftoe
@BobbyShaftoe, Yeah, I found the information about ANSI C99 used upon my book book from it's Introduction chapter. Thank you. - Nano HE

4 Answers

2
votes

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.

1
votes

You cannot have an array of variable length. Use dynamic allocation returning pointer (malloc)

1
votes

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];
1
votes

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;