You can not return an array as a result of a function no matter whether it has one dimension or two. You can return a pointer to the first element of the array. Also, strictly speaking, there are no two dimensional arrays in C. What is closest to this, is an array containing another array as elements. I.e. a definition like:
int twoDimArray[2][3];
If dimensions of such array are determined dynamically you can not define it on file scope. You can define it locally withing some function only. Such an array will be a local variable, will be stored in system stack and will disappear when control leaves the function. Personally, I'd use such a pattern. I.e. a code like:
int main() {
int rows, cols;
...
getDimensions(&rows, &cols);
// definition with dynamic dimensions in function scope is O.K.
int a[rows][cols];
init(rows, cols, a);
proceed(rows, cols, a);
...
}
where init function can be defined like:
void init(int rows, int cols, int a[rows][cols]) {
int i,j;
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
a[i][j] = i*100+j;
}
}
}
If such a pattern can not be used (the array is too big and your system stack too small for example), I'd use:
int main() {
int rows, cols;
getDimensions(&rows, &cols);
int (*a)[cols] = malloc(sizeof(int [rows][cols]));
init(rows, cols, a);
proceed(rows, cols, a);
free(a);
}
If you insist on functions returning such an array I'd use void pointers:
void *allocate2DintArray(int rows, int cols) {
return(malloc(sizeof(int [rows][cols])));
}
void *allocateAndInit(int rows, int cols) {
int i,j;
int (*a)[cols] = allocate2DintArray(rows, cols);
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
a[i][j] = i*100+j;
}
}
return(&a[0][0]);
}
int main() {
int rows, cols;
...
getDimensions(&rows, &cols);
int (*a)[cols] = allocateAndInit(rows, cols);
proceed(rows, cols, a);
...
free(a);
}