常量指针修正到一个变量变量 [英] const pointer fix to a variable variable
问题描述
我无法弄清楚如何告诉C,它我想,不会移动指针。它总是指向同一个数组。这就是说,阵列成员不恒定的,但在阵列本身是全球性的,因此,它是在一个固定的位置。
I can't figure out how to tell C that I want a pointer that will not move. It will always point to the same array. That said, the array members are not constant, but the array itself is global and so, it is at a fixed position.
所以,当我code这样的:
So, when I code this:
#include <stdio.h>
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
。我如何获得一个常量指针来完成这项工作?
I understand that the compiler thinks I need a const int v[2]
to use with a const int *iv
. How do I get a constant pointer to do the job?
如果您看到错误消息,我还没有移动指针(如光伏++
)。我只是取消引用它脱臼一些字节。
If you see the error message, I'm not even moving the pointer (like pv++
). I'm just dereferencing it dislocated some bytes.
如果我这样做:
int *pv=cpv;
*(pv+1)=5; printf("%d\n", v[1]);
printf("%p == %p !?\n", cpv, pv);
我得到这样的警告,但它的作品:
I get this warning, but it works:
constp.c:9: warning: assignment discards qualifiers from pointer target type
pointer# ./constp
5
0x601020 == 0x601020 !?
谢谢,
贝乔。
Thanks, Beco.
推荐答案
移动常量
预选赛:
int *const cpv=v;
释文: CPV
是一个常量指针 INT:在C声明的规则,这是从右到左开始在标识读
。您的版本将被读 CPV
是一个指向 INT
不变。
Explanation: in the C declaration rules, this is read from right to left starting at the identifier: "cpv
is a constant pointer to int
". Your version would be read "cpv
is a pointer to int
constant".
注意 CPV + 1
仍然会得到你一个指向 INT
在 * CPV
;做一个指针常量
仅prevents ++
, -
, + =
和 - =
它
Note that cpv+1
will still get you a pointer to the int
after *cpv
; making a pointer const
only prevents ++
, --
, +=
and -=
on it.
这篇关于常量指针修正到一个变量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!