c - Are variable array parameters allowed to have as index variables outside the function? -
my book states: "the expression used specify length of" variable array "could refer variables outside function". guess book means:
int main(void) { int xternal = 3; int variable_array[xternal]; function(variable_array); } void function(int variable_array[xternal]) { ... }
i understood variables outside function invisible it. wrong?
i presume referring variable-length-array parameters of c99.
i think textbook trying can use length specifier not other arguments of function, e.g.:
void f(int array_len, char array[array_len]);
but outside still visible, global variable:
int some_value; void f(char array[some_vaue]);
keep in mind - not mean compiler array bounds checks you. useful when use multidimensional arrays navigate on inner dimensions.
so instead of code:
int *arr = malloc(sizeof(int)*nrows*ncols); void f(int *a) { int row, int column; ...calculate row, column int value = a[row*ncols+column]; ... }
you write:
int arr[nrows][ncols]; int get_array_cols() { return ncols; } int array_rows=nrows;//or calculate... void f(int a[array_rows][get_array_cols()]) { int row, int column; ...calculate row, column int value=a[row][column]; ... }
as can see couldbe there.
basically, when compiler knows how value dimensions, can automatically prepare expression: a[row*ncols+column];
(row*ncols). example in last case, having dimensions hint, automatically compile a[row][col]
into: a[row*get_array_cols()+col]
.