I am new to C programming. I am trying to set the size of the array using a variable but I am getting an error: Storage size of 'array' isn't constant !!
01 int bound = bound*4;
02 static GLubyte vertsArray[bound];
I have noticed that when I replace bounds (within the brackets on line 02) with the number say '20', the program would run with no problems. But I am trying to set the size of the array dynamically ...
Any ideas why I am getting this error ? thanks much,
You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.
Conclusion. Size of Variable Length Arrays can be set at runtime, but we could not change their size once set. Unlike static arrays, Dynamic arrays in C are allocated on the heap and we could change their size in runtime. We need to deallocate their memory after use ourselves.
Procedure: First, we declared an array of types int with the private access specifier. Declare the count variable. Create a constructor that initializes the array of the given length.
Arrays are static so you won't be able to change it's size. You'll need to create the linked list data structure.
You are getting this error because, as the compiler told you, your array size is not constant. In C89/90 version of C language array size has to be a constant. You can't "set the size of the array dynamically". If you need a run-time sized array, you have to either allocate it manually with malloc
or use some non-standard compiler-specific approach (like alloca
function).
In C99 version of C language support for so called Variable-Length Arrays (VLA) was added. A C99 compiler would accept run-time sized array declaration for an automatic array. Yet even in C99 you can't declare a static array of run-time size, as you are trying to.
To create an array of a non-constant size (i.e. known at compile time), you need to dynamically allocate space for it using malloc()
(and correspondingly deallocate it using free()
when it is no longer required).
As others have noted, the ability to declare dynamic arrays is available in C99 compliant compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With