C++ 为什么可以';我不能通过常量指针修改变量吗?
请看以下代码:C++ 为什么可以';我不能通过常量指针修改变量吗?,c++,c,pointers,constants,C++,C,Pointers,Constants,请看以下代码: int main() { int foo = 0; const int *ptr = &foo; *ptr = 1; // <-- Error here return 0; } 是的,ptr是常量,但foo不是常量。为什么我不能给foo赋值?const int*是指向整数常量的指针 这意味着,它所指向的整数值不能使用该指针更改。即使存储该值的内存(foo)被声明为正常变量,而不是const,而是用于更改指针类型为整型常量的值的变量
int main() {
int foo = 0;
const int *ptr = &foo;
*ptr = 1; // <-- Error here
return 0;
}
是的,
ptr
是常量,但foo
不是常量。为什么我不能给foo
赋值?const int*
是指向整数常量的指针
这意味着,它所指向的整数值不能使用该指针更改。即使存储该值的内存(foo
)被声明为正常变量,而不是const
,而是用于更改指针类型为整型常量的值的变量
现在,您可以使用foo
更改该值,但不能使用该指针
指向整数常量的指针和指向整数的常量指针之间存在差异 指向整数的常量指针定义为
int*const
。初始化后,无法使指针指向其他内存
指向整数常量的指针定义为int-const*
或const-int*
。不能通过指针本身更改指针指向的值
注意: 使用
main()的标准定义
您需要区分这些:
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.
const int*ptr=&foo;//ptr
不是const
<代码>*ptr
is.int*const ptr=&foo
试试这个。@jrok我想用这个,谢谢:)所以const int*ptr
和int*restrict ptr
是一样的吗?不,restrict是完全不同的。这是一种告诉编译器内存不会被任何其他指针或变量访问的方法。参见@sunqingyao:not all,restrict
具有完全不同的含义。程序员承诺,在其作用域期间,ptr访问的任何内容都不会被另一个restrict
限定指针访问或修改。这是一个高级功能,可以启用积极的编译器优化,您可以在此阶段完全忽略它。@孙庆尧:当您将常量类型*
指针指定给非限定的类型*
或无效*
指针时,编译器会发出一个诊断,即常量
被丢弃,使用赋值运算符=
或将常量
指针作为未声明常量
的参数传递。这表明了一种危险的情况,即在承诺不修改数据的情况下接收数据时,可能会通过指定的指针修改数据。如果数据本身是const
,它将调用未定义的行为。始终const
限定不用于修改数据的指针。@CoolGuy:在C99中是:第一个const int const*const a
在同一个对象上有2个const
限定符,但按照C11 6.7.3p5中的规定是可以的:如果同一限定符在同一个说明符限定符列表中出现多次,无论是直接还是通过一个或多个typedef,行为都与只出现一次相同。注意,这是C99对C90的一个更改,C90违反了约束:同一类型限定符不得在同一说明符列表或限定符列表中出现多次,无论是直接出现还是通过一个或多个typedef出现。
int main(void) //if no command line arguments.
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.