2

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.

user1599964
  • 860
  • 2
  • 13
  • 29

6 Answers6

4

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.

Notinlist
  • 16,144
  • 10
  • 57
  • 99
3

A cast has a higher precedence that addition, c.f. here. Thus, first convert to integer pointer and then add 1*sizeof(int).

Matthias
  • 8,018
  • 2
  • 27
  • 53
2

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.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
2

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.

cedrou
  • 2,780
  • 1
  • 18
  • 23
1
*((int *)ptr+1)

that means :

  • incress the pointer to next place in memory by(sizeof(ptr))
  • then cast the pointer to pointer of integer.
  • then get the first sizeof(int) bytes!
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.

hetepeperfan
  • 4,292
  • 1
  • 29
  • 47