Declaring an array sized to a variable?

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
nigelmercier
Posts: 316
Joined: 23 Oct 2008 09:36

Declaring an array sized to a variable?

#1 Post by nigelmercier » 04 Jan 2010 13:09

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)

BikerBoy
Posts: 4
Joined: 08 Jan 2010 00:11

#2 Post by BikerBoy » 08 Jan 2010 00:40

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

Post Reply

Return to “mikroC PRO for PIC General”