7

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

4

3 回答 3

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

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

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

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

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

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

于 2012-10-12T15:31:44.797 回答
6

听起来很简单。

int a = 5;
int b = 7;

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

int difference = p_b - p_a;

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

int differenceInBytes = (p_b - p_a) * sizeof(int);

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

于 2012-10-11T22:34:48.993 回答
0

我认为这得到了抵消。

int *a = &somevar;
int *b = &anotherintvar;
int offset = b - a;
于 2012-10-11T22:34:04.390 回答