views:

149

answers:

5

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?

+6  A: 

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.

Michał Bendowski
Harsha
sizeof(arr) will return the size of the pointer, not the size of the array itself.
James Kingsbery
+3  A: 

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

pajton
+2  A: 

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.

A: 

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.

James Kingsbery
A: 

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.)

CWF