# Thread: Passing 2D dynamic arrays

1. ## Passing 2D dynamic arrays

Hi all,

Can you please point out to me how can I correctly pass a 2d dynamically allocated array into a function? My problem is that I cannot know the size of the two dimensions beforehand, and I always read that the siez of the last dimension must always be passe with the array.

I've managed to get round this by using something like:
Code:
```/* function declaration */
void function(double **array2d, int rows, int cols)

/* calling the function from main */
function(array2d, rows, cols)```
This works, but valgrind says that there is an error (which I cannot understand what it's saying on the output). I can verify that this is passed as intended (all values in the 2D array are ok), but I'm sure there's something wrong and that there should be a better way to do this.

Can anyone please explain to me a better way to do this? (if how I've done this above is indeed wrong)

Many thanks!

Spiros

2. It depends on how you do it. If you allocate an array of pointers and from that memory chunks, then you need to pass a T**.
If you allocate one big chunks of memory to account for the dimensions, then you need to pass T*.
C is a harsh mistress.

3. Thanks Elysia,

The way I'm allocating 2d arrays is this:
Code:
```    arr2d=malloc(rows*sizeof(*arr2d));
if (arr2d==NULL) {
printf("Could not allocate data array of size %i\n",rows*sizeof(*arr2d));
return NULL;
}
for (i=0; i<rows; i++) {
arr2d[i]=malloc(cols*sizeof(*arr2d[i]));
if (arr2d[i]==NULL) {
printf("Could not allocate array data[%i] of size %i\n",i, cols*sizeof(*arr2d[i]));
return NULL;
}
}```
So if I've understood right then passing a pointer to pointer is the appropriate way. Am I right?

Would you then say that there's nothing wrong with

4. That looks correct. I'm guessing arr2d is defined as an int**. You should be able to pass that in as you have it in your first post. Is valgrind complaining about the function call, or something you do inside the function?

5. A simple test case, and your actual valgrind errors (not "I got some errors I don't understand") would go a long way.

6. after couple of days of fiddling with the code, I found out that I was trying to read out of bounds of an array on the last iteration inside a loop.... That's a silly mistake that I shouldn't have done in the first place. Anyway, this makes me to check these things more vigorously to prevent this from happening again.

Thank you all!

Spiros