I am interested in line 6, 7 and 8 in the code below.
#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;
}
The output I got was:
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
I understand that the size of the lat and long pointers are 8 bytes because they are long unsigned int. But why are they only 1 byte away from each other in the memory? Shouldn’t they be 8 bytes away from each other since their size is 8 bytes? Please advice.
Thanks for all the helpful advice. I wished I could mark everyone’s as answer but I can’t. Really appreciate it.
There’s a wild mix up of completely different things and unexplainable assertions in your question.
Firstly, I don’t see an
long unsigned intpointers in your code. All pointers in your code haveint *type. Where didlong unsigned intcome from?Secondly,
latandlonare data pointers. Typically, in a non-exotic C implementation all data pointers have the same size. It doesn’t matter what they point to. On your platform data pointers have 8-byte size. That means that pointers tocharand well as pointers todoubleas well as pointers tounsigned long intwill have the same 8-byte size.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
0x7fff5fbfe9e8and0x7fff5fbfe9e0addresses. These addresses are exactly 8 bytes away:0x7fff5fbfe9e8minus0x7fff5fbfe9e0equals 8. So, where did your “1 byte away” come from?Fourthly, your code seems to suggest that
&lon+8changes the address by “8 bytes”. This is incorrect. Adding 1 to a data pointerT*shifts it bysizeof(T)bytes, which means that&lon+8actually changes the address by 8*8=64 bytes, which is exactly what you observe in your output:0x7fff5fbfea20minus0x7fff5fbfe9e0equals 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.