看看这段代码:
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
?
你需要区分这些:
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)
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)
归档时间: |
|
查看次数: |
1476 次 |
最近记录: |