Finding dimensions of a 2D array in C using pointers

南楼画角 提交于 2020-02-05 03:45:07

问题


I create a 2D array in C as follows:

int **arr;
arr = malloc(rows * sizeof(int *));

for (i = 0; i < rows; i++)
    arr[i] = malloc(cols * sizeof(int));

Now, I call:

func(arr)

In the function func, how do I calculate the row and column dimensions?


回答1:


You can't calculate it - arr is just a pointer to a pointer, there is no more information associated with it (as with all C arrays). You have to pass the dimensions as separate arguments.




回答2:


You can't. You have to pass the dimensions along with your array to the function func(arr).




回答3:


you can't (the beauty of C). (and don't try using sizeof, because that will only give you the size of the pointer) If another function needs to know the dimensions of the array, you'll have to pass along those parameters (height and width) as arguments along with the array pointer.




回答4:


A workaround for this would be to not use an array directly, but instead have a struct like this:

struct table{
    int ** arr;
    int rows;
    int columns;
}

You can then have a function which creates instances of table that takes the number of rows and columns, and handles the allocation.




回答5:


As everyone else has said, you can't. However, you may find it useful to create a structure to contain the row, column and pointer all together. This will allow you to say:

typedef struct { int rows; int cols; int **data; } myDataType;

... foo(myData);

void foo(myDataType myData) { for( i = 0; i < myData.rows; i++) {
for( j = 0; j < myData.cols; j++ ) { printf("%d,%d: %d\n", i, j, myData.data[i][j]); } } }

(I apologize if my syntax is slightly off; Perl, Java, C# and a little Ruby are jockying for elbow-space.)



来源:https://stackoverflow.com/questions/2411585/finding-dimensions-of-a-2d-array-in-c-using-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!