Int **const p的行为不像常量
int **const p does not behave like constant
我们知道在int *const p中,p是一个常量指针这意味着p保存的地址不能改变,但是在函数foo中我们改变了地址。
这怎么可能?
int main(){
int i = 10;
int *p = &i;
foo(&p);
printf("%d ", *p);
printf("%d ", *p);
}
void foo(int **const p){
int j = 11;
*p = &j;
printf("%d ", **p);
}
int **const p
表示p
为常数
p++; // Bad
p += 10; // Bad
p = newp; // Bad
但以下都可以:
if(p) *p = some_p;
if(p && *p) **p = some_int;
如果您不希望重新分配*p
,请使用以下
int * const *p;
如果您不希望更改p
和*p
,请使用:
int * const * const p;
下面将使所有p
, *p
和**p
为只读
const int *const *const p;
// 1 2 3
1: **p
是常数
2: *p
是常数
3: p
是常量
使用1或2或3或任何组合根据您的要求。
cdecl页面:如何读取复杂的声明,如int ** const p
和const int *const *const p
相关:c -这2 const是什么意思?
在您的情况下,const
应用于p
本身,而不是* p
或** p
。也就是说,您可以修改*p
和**p
,但不能修改p
。
FWIW,尝试更改p
的值,见。
查看LIVE
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- 将字符串文本常量定义为 char const* 和 wchar const*
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 非常量调用 const 成员函数失败,只读位置C++
- 为什么我不能使用与"常量字符*"相同的"const int*"创建一个 int 数组?
- 与其他静态const成员初始化静态常量成员
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- std::转换为常量字符 * 的字符串在 std::unordered_set<const 字符 * 中找不到>
- 返回非常量引用编译的 Const 方法
- 为什么使用带有 const 的方法而不是第一个没有常量的方法
- 如何使用常量变量初始化类的 const 成员变量
- 从 sub_match<常量字符 *>' 转换为'const char *const &'
- 是否允许在常量定义的对象上丢弃 const 只要它没有实际被修改?
- 为什么"const T&"不确定是常量?
- "const int <variable>" 不能出现在常量表达式中
- 当您声明"pointer type"形式(函数)参数"like an const array"时,什么是常量?
- 如何从'char const*'中删除常量