-1

我对下面代码中的第 6、7 和 8 行感兴趣。

#include <stdio.h>
#include <stdlib.h>

void go_south_east(int *lat, int *lon) {
  printf("Lat: %p, Long: %p\n", lat, lon);
  printf("Address of Lat: %p, Address of Long: %p\n", &lat, &lon);
  printf("Address of Lat: %p, Address of Long + 8 bytes?: %p\n", &lat, &lon+8);
  printf("Size of Lat: %lu, Size of Long: %lu\n", sizeof(lat), sizeof(lon));
  *lat -= 1;
  *lon += 1;
}

int main() {

  int latitude = 32;
  int longtitude = -64;
  go_south_east(&latitude, &longtitude);
  printf("Avast! Now at: [%i, %i]\n", latitude, longtitude);

  return 0;
}

我得到的输出是:

Address of Lat: 0x7fff5fbfe9e8, Address of Long: 0x7fff5fbfe9e0
Address of Lat: 0x7fff5fbfe9e8, Address of Long + 8 bytes?: 0x7fff5fbfea20 
Size of Lat: 8, Size of Long: 8

我知道 lat 和 long 指针的大小是 8 个字节,因为它们是 long unsigned int。但是为什么它们在内存中只相距 1 个字节呢?由于它们的大小是 8 个字节,它们不应该彼此相距 8 个字节吗?请指教。


感谢所有有用的建议。我希望我可以将每个人的答案都标记为答案,但我不能。真的很感激。

4

4 回答 4

2

在您的问题中,完全不同的事物和无法解释的断言混杂在一起。

首先,我long unsigned int在您的代码中看不到指针。代码中的所有指针都有int *类型。是从哪里来long unsigned int的?

其次,latlon数据指针。通常,在非外来 C 实现中,所有数据指针都具有相同的大小。他们指向什么并不重要。在您的平台上,数据指针的大小为 8 字节。这意味着指向的指针char和指向的指针double以及指向的指针unsigned long int将具有相同的 8 字节大小。

Thirdly, where did you get the idea that they are 1 byte away in memory? The very first line in your output clearly shows that they are located at 0x7fff5fbfe9e8 and 0x7fff5fbfe9e0 addresses. These addresses are exactly 8 bytes away: 0x7fff5fbfe9e8 minus 0x7fff5fbfe9e0 equals 8. So, where did your "1 byte away" come from?

Fourthly, your code seems to suggest that &lon+8 changes the address by "8 bytes". This is incorrect. Adding 1 to a data pointer T* shifts it by sizeof(T) bytes, which means that &lon+8 actually changes the address by 8*8=64 bytes, which is exactly what you observe in your output: 0x7fff5fbfea20 minus 0x7fff5fbfe9e0 equals 64.

Basically, the questions you ask are directly contradicting what you observe in your output. That's kinda makes it virtually impossible to answer. It is like showing people a red handkerchief and asking why it is green.

于 2012-09-11T17:19:35.113 回答
0

这两个地址的差正好是8,再看看。

于 2012-09-11T16:41:20.263 回答
0

它们彼此相距八个字节。PC 是字节可寻址的,而不是位可寻址的。

也就是说,编号的内存单元是字节

于 2012-09-11T16:41:59.257 回答
0

指针算法实际上将数据类型的大小添加到地址中。澄清:

int* i = 0;
i++;
printf("%p\n", i); // Prints 0x4, not 0x1

所以

printf("Address of Lat: %p, Address of Long + 8 bytes?: %p\n", &lat, &lon+8);

实际上打印 lon + 8 * sizeof(&lon) 字节的地址

于 2012-09-11T17:02:22.337 回答