• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 235
  • Last Modified:

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.


  • 2
1 Solution
Well, I'm not sure if it works for C compilers too, but
with MSVC++ you'd need to make the 'al' const, i.e.:

     int al1 = ARRAY_LENGTH;
     const int al2 = al1;
     const int al3 = ARRAY_LENGTH;
     int n1[al1];     // error
     int n2[al2];     // error
     int n3[al3];     // OK ... a real const

This is because the length of the array must be exactly
known at compile time ... therefor the size must be a const.
An 'int' is per define no const. I think the compiler tries
to replace the variable within the [] with the const number
represanted by the variable which is only possible with
'const int al3 = ARRAY_LENGTH'.

hope that helps,

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...
RaydotAuthor Commented:
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!



Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now