Passing double pointer by reference

This is a discussion on Passing double pointer by reference within the C Programming forums, part of the General Programming Boards category; Hi all
I have a 2D array created by double pointer. I would like to pass my double pointer by ...

Passing double pointer by reference

Hi all

I have a 2D array created by double pointer. I would like to pass my double pointer by reference to a function. However, I tried something like function_name(int **&matrix) but it shows compilation error. So I wonder if there is any alternative way of passing the double pointer by reference?

I also tried to use triple pointer in order to pass the double pointer by reference but it doesn't work.

because I have a 2D array and I am modifying the contents of the 2D array in the function.

As qny noted, when you pass a 2D array as an argument, it is not passed as a pointer to a pointer. Rather, it is passed as a pointer to the first array of the array of arrays.

Originally Posted by snowmoo

If I don't pass by reference, I don't get the final value outside the function.

Not quite: if you just pass the 2D array, then you are passing by reference because it means that you pass a pointer to the first array.

Alternatively, you can wrap the 2D array in a struct, then pass a pointer to the struct object instead.

EDIT:
Oh, I did not see that you edited your post #1 to include code. In this case, using a struct wrapper is advisable, otherwise it becomes hard to reason about your code. Furthermore, the struct can record the dimensions of the dynamic 2D array.

As laserlight suggested, I think it's way better to wrap the dynamic array in a struct and pass a pointer around.

I agree.

To help the OP, here is my favourite (modified to use ints), using C99 syntax. (I'll probably be scolded by Oogabooga and Adak for going overboard with this, but I believe this to be useful to the OP.)

When working with 2D tables, the edges are often a headache. Instead of CELL(table,row,column)=valueyou can use table_set(table,row,column,value) which checks its parameters and does nothing ifrow,columnis outside the table. The same goes for table_get(). Both functions return 0 if outside the table.