在C型双指针常量,正确性警告 [英] Double pointer const-correctness warnings in C

查看:128
本文介绍了在C型双指针常量,正确性警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个指针非const数据可以隐式转换的指针相同类型的常量数据

A pointer to non-const data can be implicitly converted to a pointer to const data of the same type:

int       *x = NULL;
int const *y = x;

添加额外的常量预选赛相匹配的额外间接理应以同样的方式:

Adding additional const qualifiers to match the additional indirection should logically work the same way:

int       *      *x = NULL;
int       *const *y = x; /* okay */
int const *const *z = y; /* warning */

与海湾合作委员会或锵与 -Wall 标志进行编译,但是,这会导致以下警告:

Compiling this with GCC or Clang with the -Wall flag, however, results in the following warning:

test.c:4:23: warning: initializing 'int const *const *' with an expression of type
      'int *const *' discards qualifiers in nested pointer types
    int const *const *z = y; /* warning */
                      ^   ~

为什么增加一个额外的常量预选赛放弃嵌套指针类型的限定?

Why does adding an additional const qualifier "discard qualifiers in nested pointer types"?

推荐答案

之所以常量只能添加一个层次深的是潜移默化的,是由<一个解释HREF =htt​​p://c-faq.com/ansi/constmismatch.html>问题11.10在comp.lang.c常见问题解答。

The reason why const can only be added one level deep is subtle, and is explained by Question 11.10 in the comp.lang.c FAQ.

简单地说,考虑这个例子密切相关,你的:

Briefly, consider this example closely related to yours:

const int i;
int *p;
int const **z = &p;
*z = &i;
/* Now p points to i */

下用只允许分配到丢弃预选赛第一指向的级别(所以分配到以Z 在这里是不允许的)。

您确切的例子不存在这个问题,因为常量第二个层次是指分配给 * Z 将不会被允许反正。 C ++的的允许它在这种情况下,准确,但C'S简单的规则不你的情况和上面的例子加以区分。

Your exact example does not suffer from this problem, because the const the second level means that the assignment to *z would not be allowed anyway. C++ would allow it in this exact case, but C's simpler rules do not distinguish between your case and the example above.

这篇关于在C型双指针常量,正确性警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆