-1

Hi I was learning about structs and pointers in C. Here when I am printing &tmp.z - 8 the value is different from when Iam typecasting it and printing (char *)&tmp.z - 8). I went through few articles about typecasting and pointers, but couldnt find a good reason, can anyone help me on this.?

    struct xyz
    {
        int x;
        char y;
        double z;
    }tmp;

    int main()
    {
        printf("%p\n",&tmp.z - 8);
        printf("%p\n",(char *)&tmp.z - 8);
        return 0;
    }
Ravi
  • 79
  • 1
  • 2
  • 5
  • Google "pointer arithmetic" or read about it in your C book. Maybe some useful info to be found here: http://stackoverflow.com/questions/394767/pointer-arithmetic – Lundin May 20 '16 at 06:51

1 Answers1

5

tmp.z is a variable of type double.

therefore &tmp.z gives a pointer to double.

If you subtract 1 to a pointer of type double you will go to the previous double location, i.e. 8 addresses less(if sizeof(double) is 8)). If you take &tmp.z - 8 you will get an address 64 locations less than &tmp.z

If you typecast, (char *)&tmp.z gives a character pointer. If you subtract 8 from that, you will get 8 characters before that, i.e. address 8 locations away, as a character has a size of 1.

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31