Possible Duplicate:
Why can’t I convert ‘char**’ to a ‘const char* const*’ in C?
I am curious, why can't I pass a char **
to const char **
function? Where as it is OK to pass char *
to a const char *
function it seems not to be OK to do it with double pointers. I thought it was always ok to add constness (but not ok to drop constness) but now it seems I have been wrong.
Gcc compiler is giving me the errror:
note: expected ‘const char **’ but argument is of type ‘char **’
Here is the code snippet:
int f(const char **a) { }
int main() {
char *a;
f(&a);
}
Any ideas?
Yes it is allowed. Using const in this case is good practice. By adding it to the function arguments you promise not to modify the data located at input . You could improve this answer by adding that const simply means you promise not to modify the data.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned.
The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).
Because the compiler can't guarantee safety.
See Q11.10 from the comp.lang.c FAQ: Why can't I pass a char **
to a function which expects a const char **
?
suppose you performed the following more complicated series of assignments:
const char c = 'x'; /* 1 */ char *p1; /* 2 */ const char **p2 = &p1; /* 3 */ *p2 = &c; /* 4 */ *p1 = 'X'; /* 5 */
In line 3, we assign a
char **
to aconst char **
. (The compiler should complain.) In line 4, we assign aconst char *
to aconst char *
; this is clearly legal. In line 5, we modify what achar *
points to--this is supposed to be legal. However,p1
ends up pointing toc
, which isconst
. This came about in line 4, because*p2
was reallyp1
. This was set up in line 3, which is an assignment of a form that is disallowed, and this is exactly why line 3 is disallowed.Assigning a
char **
to aconst char **
(as in line 3, and in the original question) is not immediately dangerous. But it sets up a situation in whichp2
's promise--that the ultimately-pointed-to value won't be modified--cannot be kept.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With