c - 隐式转换为 Const

标签 c

<分区>

为什么是:

int *a = 0;
int const *b = a;  /* Totally fine. */

int **c = 0;
int const **d = c; /* Generates a nasty warning. */

隐式转换为更 const 类型不是应该没问题吗?

有什么好的方法可以解决这个问题吗?基本上我有以下数组:

int **a;

而且我想在不进行丑陋的显式转换的情况下调用以下函数:

void foo1(int const **a);
void foo2(int const * const *a);

最佳答案

这很复杂。

The reason that you cannot assign a char ** value to a const char ** pointer is somewhat obscure. Given that the const qualifier exists at all, the compiler would like to help you keep your promises not to modify const values. That's why you can assign a char * to a const char *, but not the other way around: it's clearly safe to ``add'' const-ness to a simple pointer, but it would be dangerous to take it away. However, 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 */

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++ has more complicated rules for assigning const-qualified pointers which let you make more kinds of assignments without incurring warnings, but still protect against inadvertent attempts to modify const values. C++ would still not allow assigning a char ** to a const char **, but it would let you get away with assigning a char ** to a const char * const *.)

In C, if you must assign or pass pointers which have qualifier mismatches at other than the first level of indirection, you must use explicit casts (e.g. (const char **) in this case), although as always, the need for such a cast may indicate a deeper problem which the cast doesn't really fix.

http://c-faq.com/ansi/constmismatch.html

关于c - 隐式转换为 Const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552354/

相关文章:

C 字节 - 去掉多余的零(让它成为一个字符?)

c - 方括号在 sscanf 中如何工作?

C - 矩阵 > 仅正元素

C链表-如何释放内存?

c - 无法暂停循环..怎么办?

c - FindResource 工作,LoadBitmap 不工作,从磁盘工作的 LoadImage

基于J.G.的校验和算法弗莱彻

c - 为什么这里需要禁用中断?

c - 模拟简单的栈函数

c - Malloc、Calloc 用于测试我的内存极限