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
#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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Correction: the line
n = malloc(sizeof(int) * 100);
should be
n = malloc(sizeof(int) * al);
Sorry about that...
n = malloc(sizeof(int) * 100);
should be
n = malloc(sizeof(int) * al);
Sorry about that...
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.
Thanks,
Raydot.
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!