2D array of user-given size
and
pointer to an array of col
integers.
both seem to avoid the term VLA
. 4386's answer gives the "C90 forbids VLA" warning with -Wvla
.
This
int mat[row][col];
dose not work because it is auto storage.
But
int (*mat)[col];
is only a pointer to a VLA; it can be malloced and returned.
To (over-)simplify 4386's function type and to split the definition of mat
this can be done:
void *array_maker(int row, int col) // just a pointer; no dimensions, no type
{
int (*mat)[col]; // declare runtime inner dim.: ptr to VLA
mat = malloc(row * sizeof *mat); // mallocate both dims
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
mat[i][j] = i*col + j; // fill the array[][]
return mat;
}
The call from main is:
int col, row;
int (*p)[col=8]; // ptr. to VLA
p = array_maker(row=5, col); // implicit cast from void-ptr
Since a VLA is involved anyway, one might turn it around and put the array pointer into a param. This turns the function from array-maker to array-filler:
void array_filler(int row, int col, int mat[][col])
{
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
mat[i][j] = i*col + j; // fill the array[][]
}
Now the array has to be allocated by the caller - either as auto-VLA or malloced VLA-pointer or fixed-size array:
col=row=9;
int mat[row][col];
//int (*mat)[col] = malloc(row * sizeof*mat);
//int mat[9][9];
array_filler(row, col, mat);
int mat[row][col];
wrong storage duration
int* input_taker(int row, int col)
-> incompatible type warning