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
is a pointer to anything. (int *) ptr
is a pointer to int which points to the same place than ptr
, but assumes the pointee to be int
. (int *)ptr + 1
points one cell (aka. one int) further in memory. *((int *)ptr+1)
is that int.
This seems to be the short version of ptr[1]
, if ptr is an int *
pointer of course.
so
first type cast ptr to int * then increment by one, then dereference.
The first proposition: Cast ptr to int*, then increment by one and finally get the int at this address.
This is a way to handle structured data, when you only have, for example, a stream of char in input.
*((int *)ptr+1)
that means :
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.