pointer arithmetic (char*) &a[1] - (char *)&a[0] == 4

删除回忆录丶 提交于 2019-12-23 20:44:09

问题


If a is an int array, (char*) &a[1] - (char *)&a[0] is equal to 4, while &a[1] - &a[0] is equal to 1. why is that?


回答1:


Pointer math operates on the size of the data structure its pointing to. This is because if I do this:

int array[10] ;
int * p = array ;

p ++ ;

I want p pointing at the second int, not some memory halfway in between two elements.

So &a[1] is four bytes apart from &a[0] but asking it &a[1] - &a[0] asks how many ints apart it is. When you cast it to char you ask for the math in terms of the size of char.




回答2:


When you do

&a[1] - &a[0]

since a is an int array, an implicit (int *) pointer is assumed, that is

(int *)&a[1] - (int *)&a[0]

Hence since both are of type pointer to int , their difference gives 1.

But when you do-

(char*) &a[1] - (char *)&a[2]

assuming int is 4 bytes and char is 1 byte on your compiler, the difference will be four since each element of a is int and has four bytes.




回答3:


This is common problem about programmers to treat pointers as just address. This is wrong approach. For the compiler to create proper low level code it must know something more about pointer than just the memory location that it points to. That additional info is the size of object a pointer is pointing to. That all is contained in pointer type and is necessary for pointer aruthmetic. For example:

int a[25] ;
int *i_ptr = a;

printf("address of 1st element %d\n", a);
printf("address of 1st element %d\n", &a[0]);

// address of first element + sizeof(int)
printf("address of 2nd element %d\n", a+1);

// address of first element + sizeof(int)    
printf("address of 2nd element %d\n", &a[1]);

// this one is tricky
// address of first element + sizeof(25*int) ie sizeof(the whole array)
printf("address of JUST AFTER THE ARRAY %d\n", &a+1);

Last is very tricky and most programmers do not even know about it. Although a is pointing to the first element of array and has type of array element &a is something completely different. It also keeps addres of array's first element (ie. array start) but it's type is different suggesting compiler that pointer arithmetic on it will be based on array size not element size.

gives:

address of 1st element 2881388               +0
address of 1st element 2881388               +0
address of 2nd element 2881392               +4
address of 2nd element 2881392               +4
address of JUST AFTER THE ARRAY 2881488    +100

Every time you obtain address of something with & operator it has associated type with it allowing later calculations with that type of pointer.

Keep in mind that there is a pointer void * that does not have any type info associated with it and you canot perform arithmetic on it.



来源:https://stackoverflow.com/questions/20486661/pointer-arithmetic-char-a1-char-a0-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!