类型之间的初始化“const int ** const”和“int **”不允许,为什么? [英] Initialization between types "const int** const" and "int**" is not allowed, why?

查看:506
本文介绍了类型之间的初始化“const int ** const”和“int **”不允许,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用V1.8 z / OS XL C编译器,使用INFO(ALL)将警告加满,我在以下代码的第4行获得以下警告:

Using V1.8 z/OS XL C compiler, with warnings jacked-up using INFO(ALL), I get the following warning on line 4 of the code below:

WARNING CCN3196 Initialization between types "const int** const" and "int**" 
                is not allowed.


1  int foo = 0;
2  int *ptr = &foo;

3  const int * const fixed_readonly_ptr = ptr;

4  const int ** const fixed_ptr_to_readonly_ptr = &ptr;

我无法围绕我为什么收到这个警告。如果我可以分配一个int指针指向const int(第3行)的const指针,那么为什么我不能将int指针的地址赋值给一个const指针指向const int指针?我缺少什么?

I can't wrap my head around why I'm getting this warning. If I can assign an int pointer to a const pointer to const int (line 3), then why can't I assign the address of an int pointer to a const pointer to pointer to const int? What am I missing?

注意上面的代码是一个减少的例子,只是显示我遇到的问题,我遇到了少量的代码。真正的上下文是我有一个指向struct(struct s ** const)的指针的const指针,并将它作为参数传递给一个函数。who的参数被定义为const指针指向const struct(const struct s ** const)。这是因为函数不会修改结构中的数据(因此是第一个const),并且不修改始终保存传入的地址(因此第二个const)的指针参数。

Note the code above is a slimmed down example just showing the issue I'm encountering in a small amount of code. The real context is that I have a const pointer to pointer to struct (struct s** const) and am passing it as an argument to a function who's parameter is defined as a const pointer to pointer to const struct (const struct s** const). This is because the function will not modify the data in the struct (hence the first const) and it does not modify the pointer parameter which always holds the address passed in (hence the second const). The value of the pointer pointed to may be changed by the way (which is why there is NOT a third const in between the **).

推荐答案

C规则是你可以将一个指针转换为一个指向const类型的指针,但是它必须是完全相同的类型,包括const和volatile限定条件。

The C rule is that you can convert a pointer to something to a pointer to const something, but that something has to be exactly the same type including const and volatile qualifications further down the chain.

这条规则的基本原理是,如果允许这两行中的第二行:

The rationale for this rule is that if the second of these two lines were allowed:

int *ptr;

const int ** const fixed_ptr_to_readonly_ptr = &ptr;

那么这可以用来打破类型安全而不用强制转换。

then this can be used to break type safety without a cast.

const int i = 4;

// OK, both sides have type const int *
*fixed_ptr_to_readonly_ptr = &i;

// the value of fixed_ptr_to_readonly_ptr is still &ptr
// the value of ptr is now &i;

*ptr = 5;

// oops, attempt to change the value of i which is const

这篇关于类型之间的初始化“const int ** const”和“int **”不允许,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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