Reputation:
I'm in an introductory course and I am curious about casting with pointers.
What would be the difference between:
*(uint32_t*)(p)
(uint32_t)(*p)
p
is a pointer.
Upvotes: 1
Views: 118
Reputation: 105992
In former, first you are casting p
to uint32_t*
and then dereferencing it.
In latter, first you are dereferencing p
and then casting it to uint32_t
.
Upvotes: 0
Reputation: 2007
*(uint32_t*)(p)
Extracts 32 unsigned bits at the memory location.
(uint32_t)(*p)
Extracts p from the memory location in its native type, and cast that type to a 32 bit unsigned int.
The results will probably be most notable if p is a floating point type. When extracted the first way you can see the resulting bitwise format of a floating point number (sign|mantissa|exponent). When extracted the second way the number is converted to an integer, probably via some form of truncation.
Here's a fun example program:
main(){
float x = 1.25, *xp = &x;
uint32_t x1 = (uint32_t)(*xp);
uint32_t x2 = *(uint32_t *)(xp);
printf("x1 = %x\nx2 = %x\n",x1,x2);
}
and the output:
x1 = 1
x2 = 3fa00000
Upvotes: 5