为什么我不能通过const指针修改变量?

nal*_*zok 0 c pointers const

看看这段代码:

int main() {
    int foo = 0;
    const int *ptr = &foo;
    *ptr = 1; // <-- Error here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译时,clang给了我一个错误:

const.c:5:7: error: read-only variable is not assignable
Run Code Online (Sandbox Code Playgroud)

是的,ptr是const,但foo不是.为什么我不能分配值foo

art*_*rtm 8

你需要区分这些:

const int *ptr = &foo; // <-- NON-CONST pointer, CONST data.
                       // ptr _can_ point somewhere else, but what it points to _cannot_ be modified.


int * const ptr = &foo; // <-- CONST pointer, NON-CONST data.
                        // ptr _cannot_ point to anywhere else, but what it points to _can_ be modified.

const int * const ptr = &foo; // <-- CONST pointer, CONST data.
                              // ptr _cannot_ point to anywhere else, and what it points to _cannot_ be modified.
Run Code Online (Sandbox Code Playgroud)


Har*_*ris 7

const int *是一个指向整数常量指针.

这意味着,无法使用该指针更改它指向的整数值.即使存储值的内存,(foo)被声明为普通变量而不是const,但是如果类型指针指向整数常量,则用于更改值的变量.

现在,您可以使用foo而不是指针更改值.


指向整数常量的指针指向整数的常量指针之间存在差异.

指向整数的常量指针定义为int * const.初始化后,无法使指针指向其他内存.

指向整数常量的指针定义为int const *const int *.您无法通过此指针本身更改指针指向的值.


注意: 使用标准定义main()

int main(void) //if no command line arguments.
Run Code Online (Sandbox Code Playgroud)