问题
Maybe my question is easy but I am newby in C.
I create a function which read some data from a file and then pass them to a another function which parse them given number of rows and columns and create a 2D array.
I want to return this array in order to perform some operantions in its rows. How can I return a 2D array in C
Can someone give me an example or what may I did wrong?
Regards
回答1:
Beware, returning arrays in C is a beginner's trap, because it is highly dependant on the storage duration:
- static or global: no problem, but content will be overwritten by next call
- automatic : never do that! What is actually returned is a dangling pointer, because the array's life ends at the end of the return statement
- dynamic (malloc-ed): fine, but caller must free it later.
An more idiomatic way is that the caller passes an array that it owns, along with its size(s).
回答2:
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);
}
来源:https://stackoverflow.com/questions/39742103/c-function-return-2d-array