Reputation: 1
int i=20;
const char* d = "adsadasdadas"; //not use
const char* k = "use";
int delta = (char*)&k - (char*) & i;
cout << &i << endl;
cout << &k << endl;
cout << delta << endl;
cout << &i + delta << endl;
output:
000000B51D10F984
000000B51D10F9C8
68
000000B51D10FA94
&i + delta !=&k , how to fix? 68 will use as hexdecimal,and 68 change to decimal 104,+&i =000000B51D10FA94 in this case
Upvotes: 0
Views: 170
Reputation: 76678
Subtracting non-null pointers which do not point to (or one-past) the same object or into (or one-past) the same array causes undefined behavior.
Similarly, adding integers to pointers is only allowed as long as you stay within the bounds of an array (or one-past it).
&k
is a pointer to the variable k
and &i
is a pointer to the variable i
. These are completely independent variables, not part of a shared array or in any other way connected.
Therefore your program has undefined behavior. It is impossible to retrieve the difference between addresses of unrelated variables in this way and even if you used a legal approach, the result would be completely unspecified and cannot be used to retrieve a pointer to the other variable via pointer arithmetic.
As a further, more obvious issue, you are substracting the pointers in type char
, but adding the result to a int
pointer. Pointer arithmetic measures in terms of the number of elements of the corresponding array, not in bytes. The size of a char
is 1
byte and so delta
will be in units of bytes (if it wasn't UB to begin with). But pointer arithmetic in &i + delta
expects delta
to measure in number of int
s, meaning delta
should be scaled by sizeof(int)
.
Upvotes: 2