Int **const p的行为不像常量

int **const p does not behave like constant

本文关键字:常量 const Int      更新时间:2023-10-16

我们知道在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 pconst int *const *const p

相关:c -这2 const是什么意思?

在您的情况下,const应用于p本身,而不是* p** p。也就是说,您可以修改*p**p,但不能修改p

FWIW,尝试更改p,见。

查看LIVE