I am trying to understand why memory addresses for pointers increment a certain number of bytes based on datatype.
The following code creates an array of four small integers then iterates through the memory addresses holding them, byte by byte. It appears the integers are stored in the 0 byte and random values in bytes 1-3:
int ia[] = {1, 3, 4, 7};
printf("Address of Int Array 0 is: %pn", &ia[0]);
printf("Address of Int Array 1 is: %pn", &ia[1]);
printf("Address of Int Array 2 is: %pn", &ia[2]);
printf("Address of Int Array 3 is: %pn", &ia[3]);
void *addr = (void *) &ia[0];
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
addr = addr+1;
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
addr = addr+1;
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
addr = addr+1;
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
addr = addr+1;
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
addr = addr+4;
printf("nAddress: %pn", addr);
printf("Data: %dn", *((int*) addr));
Output is:
Address of Int Array 0 is: 0x7fff51b8ac30
Address of Int Array 1 is: 0x7fff51b8ac34
Address of Int Array 2 is: 0x7fff51b8ac38
Address of Int Array 3 is: 0x7fff51b8ac3c
Address: 0x7fff51b8ac30
Data: 1
Address: 0x7fff51b8ac31
Data: 50331648
Address: 0x7fff51b8ac32
Data: 196608
Address: 0x7fff51b8ac33
Data: 768
Address: 0x7fff51b8ac34
Data: 3
Address: 0x7fff51b8ac38
Data: 4
But when I put a very large integer into the array, the following happens:
int ia[] = {2147483647, 3, 4, 7};
printf("Address of Int Array 0 is: %pn", &ia[0]);
printf("Address of Int Array 1 is: %pn", &ia[1]);
....
Output:
Address of Int Array 0 is: 0x7fff51d1fc30
Address of Int Array 1 is: 0x7fff51d1fc34
Address of Int Array 2 is: 0x7fff51d1fc38
Address of Int Array 3 is: 0x7fff51d1fc3c
Address: 0x7fff51d1fc30
Data: 2147483647
Address: 0x7fff51d1fc31
Data: 58720255
Address: 0x7fff51d1fc32
Data: 229375
Address: 0x7fff51d1fc33
Data: 895
Address: 0x7fff51d1fc34
Data: 3
Address: 0x7fff51d1fc38
Data: 4
I thought possibly (although unlikely) the large integer would be broken into bytes, one per memory address for a four byte integer, in keeping with byte-addressable memory, which seems to be the representation in C. It appears from the code though that the first "memory address" is just a construct that actually holds a four byte integer. If that’s the case, why must incremented memory addresses in C increment by the size of the data type, when it appears it’s just an abstraction? Why can’t address 1 retu 4 bytes, address 1 retu 1 bytes, and so on — in particular if the data retued is smaller than the machine’s word size?
