tags:

views:

252

answers:

5

Hello, 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,

+5  A: 

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.

Mitch Wheat
+9  A: 

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.

AndreyT
+3  A: 

What you want is possible in C99; however, with earlier versions of C, you are stuck calling functions to dynamically allocate memory, e.g. alloca(3) or malloc(3).

Michiel Buddingh'
A: 

use either of these

GLubyte* vertsArray = (GLubyte*) malloc(sizeof(GLubyte) * bound);

GLubyte* vertsArray = new GLubyte[bound];

remember to free the memory when you don't need the object anymore

delete [] vertsArray;

free((void*)vertsArray;

Despite what they say in the comments I still say that you should prefer new instead of malloc if you are not 100% forced to use C. See this link for more information

Cristian
Wrong language - this is a C question. :)
Arafangion
I though the malloc and free approach were for C, and for that reason I said prefer the usage of new/delete only if supported...
Cristian
@Cristian - If your compiler supports `new` / `delete`, it is a C++ compiler, not a C compiler. And you really shouldn't be using a C++ compiler to compile C code for any number of reasons. You shouldn't encourage someone using C to use C++ "if their compiler supports it."
Chris Lutz
A: 

Thank you all very much. Just a note on my compiler and what I am trying to do.

I am geting into OpenGL ES, and am writing code using xCode. From what I have learned that xCode supports Objective-C, C, and C++. But I am not really sure what version of c/c++. I will try a few of the suggestions listed above and see what I get.