Reputation: 441
Pointers can only move in discrete steps.
int *p;
p = malloc(sizeof(int)*8);
Therefore, formally *(p+2) is calculated as *(p+2*sizeof(int)).
However If I actually code the above two, I get different results, which seems understandable.
*p = 123;
*(p+2) = 456;
printf("%d\n",*(p+2*(sizeof(int)))); \\0
printf("%d\n",*(p+2)); \\456
The question is, is this calculation implicit, done by the compiler at compile time?
Upvotes: 0
Views: 178
Reputation: 30136
Therefore, formally
*(p+2)
is calculated as*(p+2*sizeof(int))
.
No, *(p+2)
is calculated as *(int*)((char*)p+2*sizeof(int))
.
Even a brief look reveals that the only way for your statement to hold is if sizeof(int) == 1
.
Upvotes: 1
Reputation: 28654
The question is, is this calculation implicit, done by the compiler at compile time?
Yes this is implicit, when you write ptr+n
it actually advances forward n times as many bytes as size of pointee type (e.g. in case of int*
- this is 4 bytes granted integer takes four bytes on your computer).
e.g.
int *x = malloc(4 * sizeof(int)); // say x points at 0x1000
x++; // x now points at 0x1004 if size of int is 4
You can read more on pointer arithmetic.
Upvotes: 3