Runtime array sizing

Posted By: scotpip

Runtime array sizing - 10/13/14 11:10

Hi

I'm trying to define array length at runtime. In C I believe that any integer constant can be used as the array length.

In Lite-C, a #define constant compiles as expected if the value is a primitive integer

Code:
#define MYLENGTH 1
var myarray[MYLENGTH];



But use any kind of expression in the #define and you get a syntax error:

Code:
#define MYLENGTH 1 + 1
var myarray[MYLENGTH];



Even this minimal expression won't compile:

Code:
#define MYLENGTH (1)
var myarray[MYLENGTH];



New to C and to Lite-C so perhaps I'm doing something dim? Any advice much appreciated.
Posted By: sivan

Re: Runtime array sizing - 10/13/14 11:35

you need sys_malloc and sys_free to define array size runtime and allocate memory for it, and free up memory in the end.

if you later need to enlarge it, you can also use malloc with realloc and free.
Posted By: scotpip

Re: Runtime array sizing - 10/13/14 12:43

Hi sivan

My understanding is that what you're suggesting is the standard way to make a resizable array, and I'll use it if I have to.

But I'm looking for the simplest way to initialise a fixed-size array at runtime. I've seen more than one reputable source on standard C use the approach I tried above:

Code:
#define MYLENGTH (an integer expression)
var myarray[MYLENGTH];



As this seems to be legal in C it would be helpful to understand why it won't compile in Lite-C.
Posted By: sivan

Re: Runtime array sizing - 10/13/14 14:30

probably simply limited by the compiler, there are several differences exactly known only by the developers...
Posted By: scotpip

Re: Runtime array sizing - 10/13/14 17:21

Thanks sivan - I guess we just have to suck and see.

Found a workaround, so it's more of an academic issue now.

I find that if you look at older C books there are idioms for getting stuff done without the fancier features of the new compilers...
© 2024 lite-C Forums