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?

1
  • If you're open to using C++, you may use boost::multi_array for example. multi_array provides members to access the dimensions. Commented Mar 9, 2010 at 18:53

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
sizeof(arr) will return the size of the pointer, not the size of the array itself.
3

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

Comments

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.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.