L
lwawrzyniak
I'm having some fun with const and multiple indirection. Consider the
following:
int *a; /* pointer to an integer */
const int *b; /* pointer to a constant integer */
b = a; /* ok */
int **c; /* pointer to (pointer to an integer) */
const int **d; /* pointer to (pointer to a constant integer) */
d = c; /* not ok (incompatible pointer type) */
int *const *e; /* pointer to (constant pointer to an integer) */
e = c; /* ok */
This is important to me because I am trying to pass a dynamically
allocated two-dimensional "array" to a function that is not allowed to
modify the data at any level of indirection.
void f(const int * const * a) {
// *a is read-only
// **a is read-only
}
int main(void) {
int **a = NULL;
f(a); // <-- compiler warning:
// "passing arg 1 from incompatible pointer type"
// (undesired behaviour)
return 0;
}
Why are (int *) and (const int *) compatible but (int **) and (const
int **) are not? Likewise, why are (int **) and (int *const *)
compatible but (int **) and (const int *const *) are not?
How can I "constify" data pointed to by a function parameter at all
levels of indirection? (Other than wrapping it up in structs)
Please refrain from suggesting that I should just give up on using
const altogether. That would be too easy
Thanks,
Lukasz
following:
int *a; /* pointer to an integer */
const int *b; /* pointer to a constant integer */
b = a; /* ok */
int **c; /* pointer to (pointer to an integer) */
const int **d; /* pointer to (pointer to a constant integer) */
d = c; /* not ok (incompatible pointer type) */
int *const *e; /* pointer to (constant pointer to an integer) */
e = c; /* ok */
This is important to me because I am trying to pass a dynamically
allocated two-dimensional "array" to a function that is not allowed to
modify the data at any level of indirection.
void f(const int * const * a) {
// *a is read-only
// **a is read-only
}
int main(void) {
int **a = NULL;
f(a); // <-- compiler warning:
// "passing arg 1 from incompatible pointer type"
// (undesired behaviour)
return 0;
}
Why are (int *) and (const int *) compatible but (int **) and (const
int **) are not? Likewise, why are (int **) and (int *const *)
compatible but (int **) and (const int *const *) are not?
How can I "constify" data pointed to by a function parameter at all
levels of indirection? (Other than wrapping it up in structs)
Please refrain from suggesting that I should just give up on using
const altogether. That would be too easy
Thanks,
Lukasz