-2
#include<stdio.h>
int main()
{
    struct node
    {
        int a, b, c;
    };

    struct node num = {3, 5, 6};
    struct node *ptr = & num;
    printf("%d\n", *((int*)ptr + 1 + (3-2)));
    return 0;
}
haccks
  • 104,019
  • 25
  • 176
  • 264
Ayushya Rao
  • 29
  • 1
  • 5

2 Answers2

0

lets simplify

 printf("%d\n", *((int*)ptr + 1 + (3-2)));

to

 int *ip = (int*)ptr;
 int *ip2 = ip + 2;
 int v = *ip2;
 printf("%d\n", v);

ie.

'treating ptr as a pointer to a list of ints, display the value of the third one'.

The first step , treating a pointer to that struct as a pointer to an array of ints is taking advantage (misusing?) the fact that the first 3 fields are almost certainly going to be stored as 3 consecutive integers . Its a bit dodgy and I would hesitate to do it. I leave it to others to indicate whether or not its correct, in a strictly standard conforming way. I doubt it since we might have padding issues on some platforms

pm100
  • 48,078
  • 23
  • 82
  • 145
0

num is a structure that is initialized to a=3, b=5 and c=6. ptr is a pointer that points to the structure. Everything is fine until the printf line.

The construct

*((int*)ptr + 1 + (3-2)))

first casts ptr that points into a pointer to int:

(int*)ptr

The pointer points to the member a and is well-defined.

Now 1 is added to this pointer:

(int*)ptr + 1

The pointer points to just past the member a in the struct. Everything is well-defined unless this pointer is dereferenced. Finally 3 - 2 i.e. 1 is once more added to the resulting pointer.

(int*)ptr + 1

Behaviour is now undefined.

(int*)ptr + 1 + (3 - 2)    

Then this invalid pointer is dereferenced causing undefined behaviour once more.

*((int*)ptr + 1 + (3 - 2))

The reason that the number 6 was printed and that seems like it is the 3rd member of the struct was just a fluke ;)