SoftTimur
SoftTimur

Reputation: 5510

print pointers of type (int *) in a coherent way

I have this code in C:

int tab[10] = {3, 10, 5, 7, 9, 4, 9, 4, 6, 8, 0};
printf("(int*)&tab[0]=%p (int*)&tab[1]=%p (int*)&tab[1]-(int*)&tab[0]=%d\n", (int*)&tab[0], (int*)&tab[1], ((int*)&tab[1]) - ((int*)&tab[0]));

And it returns:

(int*)&tab[0]=0xbf9775c0 (int*)&tab[1]=0xbf9775c4 (int*)&tab[1]-(int*)&tab[0]=1

What I do not understand is that why the difference returned is 1 instead of 4 at the end. Could anyone tell me a way to print them (addresses and their difference) in a coherent way for (int *)?

Upvotes: 1

Views: 196

Answers (2)

August Karlstrom
August Karlstrom

Reputation: 11377

Because

((int *) &tab[1]) - ((int *) &tab[0])
=> &tab[1] - &tab[0]
=> (tab + 1) - tab
=> 1

On the other hand

((intptr_t) &tab[1]) - ((intptr_t) &tab[0])
=> ((intptr_t) (tab + 1)) - ((intptr_t) tab)
=> sizeof (int)

where intptr_t is defined in stdint.h (from the C99 standard library).

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272557

Because you're doing pointer arithmetic. And pointer arithmetic is always done in units of whatever the pointer is pointing to (which in this case is 4, because sizeof(int) == 4 on your system).

If you want to know the difference in raw addresses, then either multiply the result of the subtraction by sizeof(int), or cast the pointers to char * before doing the subtraction.

Upvotes: 2

Related Questions