c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?

标签 c pointers

<分区>

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.

关于c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496000/

相关文章:

c - 使用 MPI 的 C 语言结构数组

c - Timespec 重新定义错误

c - : in scanf?的目的是什么

c++ - 这个 C++ 代码是如何工作的

c - 在 C 中将 char 指针分配给 char 数组

c - 指针基地址的不同分配

c - 如何显示 Float64 类型的数字,最多仅显示一位小数

c++ - 使用指针将 char* 转换为 unsigned char*

c++ - 分配给派生类的基类指针和多态性

c - 引用计数如何工作?