Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c arrays: setting size dynamically?

Tags:

arrays

c

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,

like image 491
qutaibah Avatar asked May 10 '10 05:05

qutaibah


People also ask

Can you change array size dynamically?

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.

Can we increase array size dynamically in C?

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.

How do you make an array dynamic size?

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.

Can you change size of array in C?

Arrays are static so you won't be able to change it's size. You'll need to create the linked list data structure.


2 Answers

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.

like image 169
AnT Avatar answered Sep 22 '22 07:09

AnT


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.

like image 29
Mitch Wheat Avatar answered Sep 21 '22 07:09

Mitch Wheat