-1

I have read many books and answers on internet saying that if you derefer a pointer then it will give you the value stored there. But if we consider the code:

int x = 3,*ptr;
ptr = &x;
printf("%d",*ptr); /*print value in x*/
printf("%d",sizeof(*ptr));/*gives sizeof of x*/
 printf("%u",&*ptr);/*give address of x*/

If dereferencing were to give value stored in x then we would have : sizeof(3) and &3 that does not make sense whatsoever but if it were to return the variable x itself then everything would make sense: &x : gives address of x, sizeof(x) : gives size of x and

printf("%d",x); //print value in x.//

So my question is what does dereferencing a pointer give the object pointed by it or the value stored in the object?

1 Answers1

2

What is the difference between "the object" and "the value stored in the object", in your world?

The expression sizeof (*ptr), which can be written sizeof *ptr, computes the size of the value of *ptr. Since ptr has type int *, that value has type int.

Just because *ptr evaluates to 3 doesn't mean it's equivalent with the literal 3, though, it's a different expression. Taking the address of a literal makes no sense, but you can't just substitute the literal, &*ptr is the same as ptr, not &3.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • So what happens when we do *ptr? If it is not equivalent to 3 then what is it equivalent to? – user6112826 Apr 15 '16 at 13:32
  • Why must it be "equivalent" to anything like that? Why can't it just mean "the value that the pointer is pointing at", in whatever form makes the most sense in the particular context? – unwind Apr 15 '16 at 13:33