Page 1 of 1

Declaring an array sized to a variable?

Posted: 04 Jan 2010 13:09
by nigelmercier
Can I just confirm that it is not possible to declare an array size from a given variable? In other words (pseudo-code):

Code: Select all

Get number of items (num) from user
Declare char array[num] to hold this number of items
If I'm wrong, how do you do it? (Note, scope of array must be global)

Posted: 08 Jan 2010 00:40
by BikerBoy
Variables are not normally allowed when declaring arrays because the compiler needs to know how big the array is so that it can allocate memory for the array.

Also variables are usually initialised to 0 by the compiler otherwise they could contain garbage this would mean that your array could start off any size!

The best way is to decide the maximum size you will need and initialise it that big, you don't need to use all the elements of the array

Usually a constant is used ie

#define ArrSz 128

int MyArray[ArrSz]; OR int MyArray[128];

or you can pass a parameter list and the compiler will work out the size ie

int MyArray[] = {1,2,3,4} //Results in MyArray having 4 elements.

Some languages VB6 being one allows you to change the size of an array at runtime but as far as I am aware C does not