获取两个内存地址之间的差异

Mat*_*ter 7 c memory

我有一个的内存地址int *:0xbfde61e0。我还有另一个内存地址(也就是int *。如何计算两者之间的差异以用作两个位置之间的偏移量?

riw*_*alk 6

听起来很简单。

int a = 5;
int b = 7;

int *p_a = &a;
int *p_b = &b;

int difference = p_b - p_a;
Run Code Online (Sandbox Code Playgroud)

请记住,这会将差异作为 的倍数sizeof(int)。如果您想要以字节为单位的差异,请执行以下操作:

int differenceInBytes = (p_b - p_a) * sizeof(int);
Run Code Online (Sandbox Code Playgroud)

没有特定的代码或特定的应用程序,我无法获得比这更详细的信息。


Mik*_*ike 6

我真的很想了解有关您如何使用这些信息的更多详细信息。这可以提供更简洁的答案。

反正。通常会发生什么:

int a = 1;
int b = 2;
int * w = &a; //0xbfdfa900 - These are right next to each other on the stack since
int * x = &b; //0xbfdfa904   they were declared together
int y = (int)w;
int z = (int)x;

int diff = w - x; // There's a 4 byte difference in memory, but I'd get diff = 1
                  // here because the compiler knows they're ints so I'm getting
                  // diff/sizeof(int)

int pdiff = y - z; // Now I'm going to get the number of bytes difference, so 
                   // pdiff = 4 as this is due to using the address as a raw value
Run Code Online (Sandbox Code Playgroud)

有如何在两个指针之间获得两个不同的偏移量。现在很明显,如果您的指针在堆栈上不相邻,则值开始更改:

int a = 1;
int arr[5] = {0};
int b = 2;
int * w = &a; //0xbfdfa900 - These are right off by 24 bytes (6 * sizeof(int))
int * x = &b; //0xbfdfa918   because we have 5 more ints there
Run Code Online (Sandbox Code Playgroud)

两者之间的距离和类型越多,我们就越会失去两个变量之间明显的“偏移”,换句话说,这开始变得毫无意义。这就是为什么指针算术实际上只适用于数组(因为它们是特定类型的已知连续内存)。所以在你的情况下:

int * one = &somenum;      // 0xbfde61e0
int * two = &someothernum; // 0xbfbf69e0
printf("%d\n", (int)two-(int)one);
2029568 bytes
Run Code Online (Sandbox Code Playgroud)

这些距离很远。所以你可以减去它们,但我不确定你为什么要这样做。