获取两个内存地址之间的区别

时间:2012-10-11 22:33:00

标签: c memory

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

3 个答案:

答案 0 :(得分:4)

听起来很简单。

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);

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

答案 1 :(得分:4)

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

反正。通常会发生什么:

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

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

答案 2 :(得分:0)

我认为这会得到抵消。

int *a = &somevar;
int *b = &anotherintvar;
int offset = b - a;