1

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?

user2698
  • 315
  • 1
  • 3
  • 8
  • If you're open to using C++, you may use boost::multi_array for example. multi_array provides members to access the dimensions. – amit kumar Mar 09 '10 at 18:53

5 Answers5

8

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
  • 2,711
  • 1
  • 23
  • 32
  • Thanks. But, if I had instead declared it as `int arr[rows][cols]`, then `sizeof(arr)` would return the correct value, right? Using the same logic, cant I use `sizeof(&arr[0][0])` when I dynamically allocate? – user2698 Mar 09 '10 at 18:50
  • sizeof(arr) will return the size of the pointer, not the size of the array itself. – James Kingsbery Mar 09 '10 at 18:59
3

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

pajton
  • 15,828
  • 8
  • 54
  • 65
2

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.

user289895
  • 21
  • 1
0

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
  • 7,298
  • 2
  • 38
  • 67
0

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
  • 2,067
  • 1
  • 13
  • 4