const和指针用C [英] const and pointers in C
问题描述
常量与指针的使用可以使指针对象没有使用有问题的指针引用它修改。但是,为什么我也不能修改一下指针不直接指向?
The use of const with a pointer can make the pointee not modifiable by dereferencing it using the pointer in question. But why neither can I modify what the pointer is not directly pointing to?
例如:
int a = 3;
const int* ptr = &a;
*ptr = 5;
将无法编译。但是,为什么
will not compile. But why does
*(ptr + 2) = 5;
也不能编译?我不会改变什么指针指向。结果我们也是这样不得不说,以这样的方式使用常量的指针,不仅使不可修改什么指针指向(通过取消引用指针),而且还别的,对此我们ADRESS开始使用指针?
also not compile? I'm not changing what the pointer is pointing to.
So do we have to say that using const with a pointer in such a way not only makes not modifiable what the pointer is pointing to (by dereferencing the pointer) but also anything else, to which the adress we get using the pointer?
我知道,在这个例子中,我试图访问未分配的内存,但是这仅仅是为了讨论的方便。
I know that in the example I'm trying to access not allocated memory, but this is just for the sake of discussion.
推荐答案
PTR +2
只是有相同类型 PTR
即是一个指向一个常量
对象。
ptr +2
simply has the same type as ptr
namely is a pointer to a const
object.
指针运算中假设被指向的对象是所有相同的基本类型的数组。这种类型包括常量
资格。
Pointer arithmetic supposes that the object that is pointed to is an array of all the same base type. This type includes the const
qualification.
这篇关于const和指针用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!