Mail Archives: djgpp/1997/02/19/16:01:57
Dim Zegebart (zager AT post DOT comstar DOT ru) wrote:
: void foo(void)
: {
: int i=0;
: int arr[i];
: for(i=0;i<10;i++)
: {
: arr[i]=i;
: }
: }
This won't work; it gives a segmentation fault. You're effectively declaring
'arr' to be an array of 0 integers, then attempting to access arr[0], arr[1],
... arr[9].
The syntax is correct, though, I think. But it's a bit pointless in this
context; the 'int arr[i]' could be replaced with 'int arr[10]', having the
same effect. The whole point of variable length arrays is that the length
of the array cannot be determined at compile-time, and may vary at run-time.
For instance, putting a parameter into your function, then using this as the
size of the array (and the limit of the for loop).
Note that variable length arrays are a gcc extension. For portability you
should use:
int *arr=(int *)malloc(i*sizeof(int));
instead of 'int arr[i];', and remember to free(arr) before the end of the
function.
--
George Foot <gfoot AT mc31 DOT merton DOT ox DOT ac DOT uk>
Merton College, Oxford.
- Raw text -