const指针修复变量变量
我无法弄清楚如何告诉C我想要一个不会移动的指针。 它总是指向同一个数组。 也就是说,数组成员不是常量,但数组本身是全局的,因此,它处于固定位置。
所以,当我编码时:
#include int v[2]={0, 1}; const int *cpv=v; int main(void) { v[1]=2; printf("%d\n", v[1]); *(cpv+1)=3; printf("%d\n", v[1]); cpv[1]=4; printf("%d\n", v[1]); }
并得到这个错误:
constp.c: In function 'main': constp.c:9: error: assignment of read-only location '*(cpv + 4u)' constp.c:10: error: assignment of read-only location '*(cpv + 4u)'
我知道编译器认为我需要一个const int v[2]
来使用const int *iv
。 如何获得一个常量指针来完成这项工作?
如果你看到错误信息,我甚至没有移动指针(如pv++
)。 我只是取消引用它错位了一些字节。
如果我这样做:
int *pv=cpv; *(pv+1)=5; printf("%d\n", v[1]); printf("%p == %p !?\n", cpv, pv);
我得到了这个警告,但它有效:
constp.c:9: warning: assignment discards qualifiers from pointer target type pointer# ./constp 5 0x601020 == 0x601020 !?
谢谢,Beco。
移动const
限定符:
int *const cpv=v;
说明:在C声明规则中,从标识符开始从右到左读取:“ cpv
是指向int
的常量指针”。 您的版本将被读取“ cpv
是指向int
常量的指针”。
请注意, cpv+1
仍然会在*cpv
之后获得指向int
的指针; 制作指针const
只会阻止++
, --
, +=
和-=
。
您正在使用指向const的指针,而不是const指针。
const int * cpv = v;
应该变成:
int * const cpv = v;
指针有点“向后看”:
const int * p;
在这种情况下,“ p
”是指向“ const int
”的(变量)“指针”。 从字面上看,向后读,“ *
”表示“指针”: “指针…到int const”。
奇怪的是,以下是同样的事情:
int const * p; // same thing
向后读,它说, “指针……到const int” (同样的事情)。
所以,如果你希望你的指针是“常量”(不是变量),你需要向后读取并做到这一点:
int * const p; // p cannot change
现在,“ p
”是指向非常数整数的常量指针。 不是belabor,而是向后看,即“const指针……到int”。
使用上面的“相同的东西”示例,我们现在可以有一个常量指针指向一个常量整数(以下是相同的):
const int * const p; int const * const p;
你应该向后看它们,并且它们都说同样的话, “将指针指向常数int”。
int * const cpv=v;
话虽如此,为什么你需要指针呢? 如果要直接访问变量v,编译器将能够做得更好。 如果通过指针,生成的代码必须在每次访问数组时从内存中读取指针。
#include int v[2]={0, 1}; //const int * cpv=v; // cpv is a pointer to int const // int const * cpv=v; // cpv is a pointer to const int == same as above == int *const cpv=v; // cpv is a constant pointer to int // int const *const cpv=v; // cpv is a constant pointer to const int //const int *const cpv=v; // cpv is a constant pointer to int const == same as above == //const int const *const cpv=v; // == same as above == int main(void) { v[1]=2; printf("%d\n", v[1]); *(cpv+1)=3; printf("%d\n", v[1]); cpv[1]=4; printf("%d\n", v[1]); }