开发者

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

开发者 https://www.devze.com 2023-03-04 23:44 出处:网络
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*)&

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 instea开发者_运维知识库d of 4 at the end. Could anyone tell me a way to print them (addresses and their difference) in a coherent way for (int *)?


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消