Passing Multidimensional Arrys in functions as const

I know that this topic has been discussed in other posts, but I have an additional question concerning the case when you want to pass a nested new created array as const.

For example:

1.- we create the 2 dimension array, like this (there are others way to do it, but I would like to discuss this):

int **q;
q=new int *[3];
for (int i=0;i<3;i++){
q[i]=new int[3];
}

2.- then you have a function that will recive the 2D matrix q as “const”:

void func (int **q){

//do something here, without modifying q
}

3.- Eventually you free the heap:

for(int i=0;i<3;i++){
delete [] q[i];
}
delete []q;


My question is: how top pass q as const?
If you don't want the integer values changed, you would void func(const int ** q); if you would like to keep the function from altering the pointers to the arrays inside the array you would void func(int * const * q); finally, to merge the two previous cases you would void func(const int * const * q).
Thank you.

But the first option you mention const int **q (actually this is the option I am interested in) does not work (my compiler does not admit it, MSC C++ compiler); I tried it time ago but it really does not work

Any thought?
I have tried this with Visual studio 2008. it passes q as const only. No problem with Visual studio...

If it is not working in MSC C++ compiler means, Can try with

void func (int ***q).

we can pass address of two dimenstional array. so that the content of array wont change.

How are you writing the call to the function?

This way: func(q)?

Thanks


func(&q);
Last edited on
This call

func(q)

works with a function signature

func(int **p)

but not with

func(const int **p).

What you are saying

func(&q)

does not work with neither of the signatures.

Please remember the way I am constructing the 2D matrix.


if function declaration is

func(int ***p)
{

//inside the function get the adress of 2D matrix. using pointer can process.

}

then function call will be

int **q;

//some initialization for 2D matrix. then the address of q send to the function.

func(&q);


Like this.


Last edited on
Topic archived. No new replies allowed.