为什么指向const的指针所指向的位置可由其他变量赋值?

Pra*_*mar 2 c pointers

我写了这段代码

#include <stdio.h>
int main() {
     int b = 15;
     const int *foo = &b;
     //b = 20;
     *foo = 20;
     printf("%d", *foo);
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

这意味着foo指向的位置无法更改.这意味着b无法改变.但是当我取消注释时b = 20.它没有显示任何错误,我得到了输出20.在这段代码中我得到了这个错误

main.c: In function 'main':
main.c:15:10: error: assignment of read-only location '*foo'
      *foo = 20;
Run Code Online (Sandbox Code Playgroud)

如果*foo那是b只读位置,为什么我可以改变它的值b = 20

hac*_*cks 7

是什么

 int b=15;
 const int* foo=&b;   
Run Code Online (Sandbox Code Playgroud)

意思?

它的意思是,

  • b是一个可修改的int对象.
  • &b有类型int *.foo转换&b为类型的声明const int *.这是有效的资格转换.
  • int指向的对象foo不得使用修改foo.

上述资格转换不会使声明无效b,即它仍然可以修改.b仍可用于更新其值但*foo不能使用.

认为const是一种承诺.您向编译器承诺,您不会更改指定位置的值foo,但没有人阻止您通过其他方式更改该位置的值来破坏该承诺.

  • 你不能使用`foo`来改变它指向的东西.没有什么可以阻止你改变其他合法机制指出的东西.使用`b`是修改`foo`指向的位置的合法机制. (2认同)
  • @PradeepKumar:我们可以看到你没有得到它.什么是难以解决为什么你没有得到它.`foo`是指向常量值的指针意味着你不能使用`foo`来改变它指向的内容.但是`b`并不是一成不变的.它可以改变.它只是不能使用`foo`来改变. (2认同)

Ste*_*ner 7

我认为chqrlie是正确的,他说错误消息"只读位置'*foo'的分配"是误导性的.实际上,const int *foo(即指定为指向a的指针const int)并不意味着指针所寻址的内存本身就是不可变的; 它只是意味着指针寻址的内存不能通过这个指针改变; 但是,它可能会以其他方式改变.您可以定义,例如第二个指针int *foo2 = &b,您可以通过该指针更改所寻址的值foo2.

因此,您可能会将指针视为与特定内存地址处的值的单独视图,并且可以将视图声明为只读.但是,这不会影响特定内存地址本身的值是否不可变:

int main()
{
    int b=15;  // b is mutable
    const int* foo=&b; // *foo is immutable; b remains mutable
    int *foo2=&b; // *foo2 is mutable
    b=20;  // allowed, since b is mutable
    *foo=20; // not allowed, since "*foo" is immutable, even if the value to which it points (i.e. b) would be mutable
    *foo2=20; // allowed, since "*foo2" is mutable

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然没有被问到,反过来说,你实际上可以将一个定义为不可变的,然后不得以任何方式改变这个值; 如果以某种方式通过写入其内存地址来操纵该值,则行为未定义:

const int c = 15; // c is immutable
int* bar = &c; // warning: discards const qualifier
printf("%d\n", c);
*bar = 20;  // undefined behaviour from here on; modifying a const value is not allowed.
printf("%d\n", c); // undefined behaviour; good chance that it still prints 15, because a compiler might have relied on the fact that c is 15 and immutable
printf("%d\n", *bar); // undefined behaviour; probably printing 20?
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.