A few things to point out.
First of all, you cannot assign an array object like you are here:
char A[WIDTH][HEIGHT]; A=rand_grid(WIDTH,HEIGHT);
Array type objects are not modified.
Secondly, functions in C cannot return array types. They can return pointers to arrays:
char (*foo(int width))[HEIGHT] { char (*newArr)[HEIGHT] = malloc(sizeof *newArr * width); return newArr; }
The syntax is a bit confusing; it reads like
foo -- foo foo(int width) -- is a function -- taking an int parameter *foo(int width) -- returning a pointer (*foo(int width))[HEIGHT] -- to a HEIGHT-element array char (*foo(int width))[HEIGHT] -- of char
For C89, HEIGHT in the above snippet should be a constant integral expression of compilation time (either a macro, a numeric literal, or an arithmetic expression consisting of macros and / or numeric literals). I am not sure if this is also true for the C99.
Based on the fragment that you posted, you want to make an array that you have already allocated and initialize its contents. Remember that in most contexts, an array type expression will be implicitly converted to a pointer to the base type. IOW, if you pass an N-element array from T to a function, what the function actually receives is a pointer to T:
void foo (T *p) {...} ... T arr[N]; foo(arr);
For 2-dimensional arrays this is a bit uglier:
void foo (T (*p)[M]) {...} ... T arr[N][M]; foo(arr);
It also depends on what M is known at compile time, which limits the usefulness of the function. What you need is a function that can work with a 2-dimensional array of arbitrary size. The best way I know this is to not pass a pointer to the array, pass the address of the first element in the array [1], and pass the number of rows and columns as separate parameters:
void foo(T *base, size_t rows, size_t cols) {...} ... T arr[N][M]; foo (&arr[0][0], N, M);
So your rand_grid function will look something like this:
void rand_grid(char *base, size_t rows, size_t cols) { size_t i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { base[i*cols+j] = initial_value(); } } } int main(void) { char A[WIDTH][HEIGHT]; rand_grid(&A[0][0], WIDTH, HEIGHT); ... }
- Even if the expressions
&A[0][0] and A give the same value (base address A), the types of these two expressions are different. The first expression evaluates to a simple pointer to char ( char * ), and the second evaluates to a pointer to the 2nd array of char ( char (*)[HEIGHT] ).