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.
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]);
}
And get this errors:
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)'
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.
If I do this:
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.