2

I started studying C++ at university 2 months ago, and I'm trying to figure out how to pass a dynamic 2d array (pointer to pointer) to a function as an input parameter. I have this dynamic 2d array:

int **p;
p = new int*[R];
for(i=0; i<R; i++)
    p[i] = new int[C];

Now I want to pass this pointer p to a function as an input parameter, using const. I mean that I want the function not to be able to modify the elements of the matrix.

I tried like that:

void func(const int **p) {
}

But i get this error:

main.cpp:19:11: error: invalid conversion from 'int**' to 'const int**' [-fpermissive]

main.cpp:9:6: error: initializing argument 1 of 'void func(const int**)' [-fpermissive]

I tryied using typedef and it works, but it's not constant. If i do like that:

typedef int** abc;

void func(const abc p);

main() {
abc p;
...
func(p);
}

The source compiles but function 'func' is able to modify values of "p matrix"; I want p to be an input parameter, it has to be read-only!

Please, how can I pass a pointer-to-pointer to a function flagging the elements as read-only?

Thank you in advance for you help and sorry for my bad english.

3 Answers 3

3

Your const int **p should be a const int * const *p. The conversion from const int ** to int ** isn't allowed to be implicit, because it could violate the constness of the values being pointed to. To see why, look at the following code extract taken from the C standard (§6.5.16.1):

const char **cpp;
char *p;
const char c = 'A';

cpp = &p;       // constraint violation
*cpp = &c;      // valid
*p = 0;         // valid

If cpp = &p was a valid assignment, the subsequent code would be able to set the value of c to 0, despite the value being a const char.

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

Comments

2
void func(const int * const *p) {
}

1 Comment

Could you please also provide me a short explaination of this? Thank you so much.
1

Try this:

typedef const int *cint_ptr_t  ;

void func(const cint_ptr_t  *p) {
}

Keep in mind that you want to be const the elements of your 2D array and the pointers to the beginning of each row

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.