Reputation: 73
Assuming sizeof
integer as 4 bytes and sizeof(int *) as 8 bytes , I'm not getting why ptr +1 moves forward by the size of 8 bytes and ptr[0]+1 moves forward by the size of 4 bytes.
int main()
{
int a[] = {1, 2, 3};
int *ptr[3]; //array of 3 elements pointed to integer
int *b;
ptr[0] = a;
printf("a: %lu\n", a);
printf("a + 1: %lu\n\n", a+1);
printf("ptr: %lu\n", ptr);
printf("ptr + 1: %lu\n", ptr+1);
printf("ptr[0]: %lu\n", ptr[0]);//ptr[0] holds base address of array a
printf("ptr[1]: %lu\n\n", ptr[0] + 1 );
printf("&ptr: %lu\n", &ptr);
printf("&ptr + 1: %lu\n", &ptr+1);
}
Upvotes: 1
Views: 551
Reputation: 1485
If I understand your question correctly, you have an array of pointers to int
(int *
). You expect the address of the second element to be four bytes higher than the address of the first element, and you are asking why this is not so?
If that is indeed your question, the answer is that the size of a pointer is not necessarily the same as the size of an int
.
On a 64-bit compiler, the size of a pointer would usually be 8 bytes, while the size of an int is likely to be 4 bytes.
You can print out sizeof(int)
and sizeof(int *)
to see this clearly.
Upvotes: 4