[英]I have question about C++ memory address difference type calculate memory address offset ?
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? &i + delta !=&k ,如何解决? 68 will use as hexdecimal,and 68 change to decimal 104,+&i =000000B51D10FA94 in this case
68 将用作十六进制,68 更改为十进制 104,+&i =000000B51D10FA94 在这种情况下
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
. &k
是指向变量k
的指针,而&i
是指向变量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.作为另一个更明显的问题,您正在减去
char
类型的指针,但将结果添加到int
指针。 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). char
的大小为1
个字节,因此delta
将以字节为单位(如果它不是以 UB 开头)。 But pointer arithmetic in &i + delta
expects delta
to measure in number of int
s, meaning delta
should be scaled by sizeof(int)
.但是
&i + delta
中的指针运算期望delta
以int
的数量来衡量,这意味着delta
应该按sizeof(int)
缩放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.