jn**@hotmail.com (JNY) writes:
Is it possible to declare an array with variable indeces?
i.e.
int x = 4;
int myArray[x];
for (j = 0;j < 5;j++)
{
myArray[j] = j;
}
x = 5;
for (j = 0;j < 6;j++)
{
myArray[j] = j;
}
In C99 (but not in C90), you can declare a variable-length array
(VLA). The length of a VLA can be a non-constant expression, but it's
evaluated when the array is created. The size of the array cannot be
changed after that. In your sample code, changing the value of x
doesn't affect the array.
Note that the C99 standard is not yet widely implemented. Pre-C99
compilers don't support VLAs (though gcc has its own, slightly
incompatible, version of variable-length arrays).
If you know your array can never exceed some constant size, you can
just declare an array of that size and keep track of how much of
you're currenty using. Otherwise, you can use malloc() for the
initial allocation and realloc() to adjust the size.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.