Consider the following C
code
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // ptr points to the internal pointer variable of `arr`, that is, the address of its first array element, 10.
printf("The address of the first int array element is : %p\n"
"The stored value (.i.e., the memory address) of the pointer is: %p\n",
(void*)&arr[0], (void*)ptr);
printf("The memory size the a int variable is: %zu bytes, which is equal to %lu bits (each byte has 8 bits).\n"
"Since `ptr` is a int pointer, the command `ptr = ptr + 1` shifts stored memory address of `ptr` in %zu bytes.\n\n",
sizeof(int), 8*sizeof(int), sizeof(int));
ptr = ptr + 1; // Move ptr to the memory address of the next integer (20) (instead, you could use `ptr++`)
printf("The address of the first int array element is : %p\n"
"The stored value (.i.e., the memory address) of the pointer is: %p\n\n",
(void*)&arr[0], (void*)ptr);
return 0;
}
It prints:
The address of the first int array element is : 0x7ffe100ee500
The store value (.i.e., the memory address) of the pointer is: 0x7ffe100ee500
The memory size the a int variable is: 4 bytes, which is equal to 32 bits (each byte has 8 bits).
Since `ptr` is a int pointer, the command `ptr = ptr + 1` shifts stored memory address of `ptr` in 4 bytes.
The address of the first int array element is : 0x7ffe100ee500
The store value (.i.e., the memory address) of the pointer is: 0x7ffe100ee504
However it contradicts the way I am reasoning over memory address and the system memory's architecture:
0x7ffe100ee500
C
int
variable is 4-bytes-sized, one memory address is enough to store it (I suppose the remaining 4 bytes in 0x7ffe100ee500
is simply ignored).ptr = ptr + 1
makes the the pointer's stored value (i.e., the memory address 0x7ffe100ee500
) move forward 4 bytes.0x7ffe100ee501
would be enough.However, I am getting 0x7ffe100ee504
, as if each memory address contained 1 byte only. Can someone please give me a help to understand it?
I am on a 64-bit system, which means that each memory address stores 64 bits, or equivalently, 8 bytes.
False. Each addressable memory address, by definition, stores 1 byte. Having a 64 bit system means that an address is a 64 bit value.
So given your example of a 32 bit int
whose starting address is 0x7ffe100ee500, that value occupies the addresses 0x7ffe100ee500, 0x7ffe100ee501, 0x7ffe100ee502, and 0x7ffe100ee503.