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

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

它听起来很简单。

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

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

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

无论如何。 通常会发生什么:

 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 

这是一个很好的距离。 所以你可以减去它们,但我不确定你为什么要这样做。

我认为这会得到抵消。

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