Link to home
Start Free TrialLog in
Avatar of Raydot
Raydot

asked on

What don't I get about variable declaration?

I'm writing a C program that starts like this:

#include <stdio.h>
#define ARRAY_LENGTH 20

int main(void) {
     int al = ARRAY_LENGTH;
     int n[al];
 ...

Well the code won't let me do this.  It doesn't see al as equalling ARRAY_LENGTH or 20.  I thought it was a Borland glitch, but MSVC gives the same error!

I know C has that voodoo that requires the variables to be declared in the program "head" instead of any old place.  It's a 100 point question, so I'm not only looking for how to make the above code work, but a concrete explanation of what the rules are for declaring variables.

Thanks,

Raydot
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pjknibbs
pjknibbs

Raydot: If what you're basically looking for is to create an array whose length is only known at runtime, it isn't possible to do it directly--a declared array in C must be of a fixed length; there are no exceptions to this rule. If you want to dynamically size an array you're going to have to do it manually, e.g.:

int *n;
int al = 100;

n = malloc(sizeof(int) * 100);
n[0] = 13;
n[99] = 127;

or something like that. You can use code like this because a C array is defined as being just a pointer to the first element of the array. Obviously you're going to have to remember to free() the array when you've finished using it!
Correction: the line

n = malloc(sizeof(int) * 100);

should be

n = malloc(sizeof(int) * al);

Sorry about that...
Avatar of Raydot

ASKER

I'm not sure you gave me 100 points worth of answer, considering the question, but I did actually find this exact answer this morning, so you must be right!

Thanks,

Raydot.