Ayush Goel
Ayush Goel

Reputation: 441

Calculating the address: pointer + non-negative number

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

Answers (2)

barak manos
barak manos

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

Giorgi Moniava
Giorgi Moniava

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

Related Questions