October 11th, 2003, 09:40 AM
declare array with global int
I have an array that is created in a function (not main). I also have an int that is declared outside of main, lets call it x. Now the value for x is computed in funtion 1 and the array is declared in function 2. When I want to initialize the array I put:
int array[x] This gives me three errors: error C2057: expected constant expression, error C2466: cannot allocate an array of constant size 0 and error C2133: 'cpu' : unknown size. I have already declared arrays before in the program using #deinfe but I cant this time since the value is not known ahead of time. What can I do about this?
This is not myactual code but I hope it clears up any confusions from my explanation.
Thanks alot in advance!
function1(); //the value of x is computed
October 11th, 2003, 10:02 AM
Re: declare array with global int
error C2057: expected constant expression:
you cannot use a variable for a dimension in an array declaration unless it is constant.
C2466: cannot allocate an array of constant size 0:
x is uninitialized (since the size of the array for the declaration is determined at compile time, not run time), so x is 0.
C2133: 'cpu' : unknown size:
the compiler does not know the size of the variable cpu - you do not have a variable cpu in your program listing, so you must have omitted it from this post. Take a look at this MSDN page for more information.
The solution is dynamic memory allocation. Use new or malloc. You specify the size when the time comes to allocate the memory. Make sure you de-allocate it (free it) when it is no longer needed. Use delete or free.
October 11th, 2003, 12:50 PM
The compiler must know the value of x at compile-time in order to create the array. That is the bottom line.
So the choice is to either define X at compile time or to create the array dynamically.
October 11th, 2003, 03:09 PM
ANSI C99 supports variable length arrays. ANSI C89 does not. Most compilers are not yet C99 compliant. GNU GCC 3.x allows them. But generally I'd currently stick to C89 standards to ensure portability. Use dynamic memory allocation:
Unfortunately you'll have to calculate the indices, as this is regarded as a 1D array, you cannot use 2D array notation. To dynamically create a true 2D array:
int* array ;
array = (int*)malloc( sizeof(int) * x * 4 ) ;
Now array is an array of integer pointers each pointing to a 4 integer array within block ;
int** array ;
int* block ;
int i ;
block = (int*)malloc( sizeof(int) * x * 4 ) ;
array = (int**)malloc( sizeof(int*) * x )
for( i = 0; i < x; i++ )
array[i] = &block[i * 4] ;
You can now use 2D array notation:
array for example is the second integer in the sixth block of four integers.