Possible Duplicate:
Why can’t I convert ‘char**’ to a ‘const char* const*’ in C?
我很好奇,为什么我不能将 char **
传递给 const char **
函数?虽然可以将 char *
传递给 const char *
函数,但使用双指针似乎不行。我认为添加 constness 总是可以的(但不可以删除 constness)但现在看来我错了。
Gcc 编译器给我错误:
note: expected ‘const char **’ but argument is of type ‘char **’
这是代码片段:
int f(const char **a) { }
int main() {
char *a;
f(&a);
}
有什么想法吗?
因为编译器不能保证安全。
请参阅 comp.lang.c FAQ 中的 Q11.10: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 a const char **
. (The compiler should complain.) In line 4, we assign a const char *
to a const char *
; this is clearly legal. In line 5, we modify what a char *
points to--this is supposed to be legal. However, p1
ends up pointing to c
, which is const
. This came about in line 4, because *p2
was really p1
. 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 a const char **
(as in line 3, and in the original question) is not immediately dangerous. But it sets up a situation in which p2
's promise--that the ultimately-pointed-to value won't be modified--cannot be kept.