Suppose ptr is some pointer then :
*((int *)ptr+1)
means what:
first type cast ptr to int * then increment by one, then dereference.
OR
first increment ptr by one, then typecast, then dereference.
Suppose ptr is some pointer then :
*((int *)ptr+1)
means what:
first type cast ptr to int * then increment by one, then dereference.
OR
first increment ptr by one, then typecast, then dereference.
ptr
何かへのポインタです。(int *) ptr
は、と同じ場所を指すintへのポインタですが、ポインタは。ptr
であると想定していますint
。(int *)ptr + 1
メモリ内のさらに1つのセル(別名1つのint)を指します。*((int *)ptr+1)
そのintです。
A cast has a higher precedence that addition, c.f. here. Thus, first convert to integer pointer and then add 1*sizeof(int)
.
もちろんptr[1]
ptrがポインタであれば、これはの短いバージョンのようです。int *
それで
最初にキャストptrをint*と入力し、次に1ずつインクリメントしてから、逆参照します。
最初の命題:ptrをint *にキャストし、次に1ずつインクリメントして、最後にこのアドレスでintを取得します。
これは、たとえば入力にcharのストリームしかない場合に、構造化データを処理する方法です。
*((int *)ptr+1)
つまり:
This codes shows pretty much what you are doing:
#include<stdio.h>
int main( ) {
int onetwo[] = { 1, 2};
/*create a void pointer to one two*/
void* ptr = (void*) onetwo;
printf ( "pointer onetwo[0] = %p\n", &onetwo[0] );
printf ( "pointer onetwo[1] = %p\n", &onetwo[1] );
/* since you are doing pointer arithmetics
* it's really important you cast ptr back to
* int* otherwise the compiler might not
* return a pointer to onetwo[1] but if sizeof(int)
* is 4 bytes
*/
printf ( "value = %d\n", *( (int*)ptr + 1) );
/* in this print statement ptr is still a void* when
* it is incremented, therefore it points between
* onetwo[0] and onetwo[1]
*/
printf ( "value = %d\n", * ((int*)( ptr + 1)) );
/*casting to int* is for illustration properties */
printf ( "This points between onetwo[0] and onetwo[1] because it's at %p\n", (int*) (ptr + 1));
return 0;
}
output on my machine yields :
~/programming/stackoverflow$ ./p
pointer onetwo[0] = 0x7fffdd8e2fc0
pointer onetwo[1] = 0x7fffdd8e2fc4
value = 2
value = 33554432
This points between onetwo[0] and onetwo[1] because it's at 0x7fffdd8e2fc1
I hope this demonstrates some of the effects of pointer arithmetics.