Thursday, July 30, 2009

C programming - Consider an int variable x and consider a pointer float* p=(float*)&x pointing to x.?

Consider an int variable x and consider a pointer float* p=(float*)%26amp;x pointing to x. If we store a float value 2.35 in x directly using x = 2.35 or indirectly using *p=2.35, will we get the same bit pattern stored in x in both cases or instead different patterns? Explain your answer, just “Yes” or “No” is not sufficient.

C programming - Consider an int variable x and consider a pointer float* p=(float*)%26amp;x pointing to x.?
The bit pattern for x = 2.35 is not the same as *p = 2.35.





This is because you defined x as a int and when you assign 2.35 (a float) to x (an integer) the C language will automatically cast the value of 2.35 to an int. So x will be assigned the value of 2.





However, since you defined p as a pointer to a float and since x is 4 bytes and a float is 4 bytes, you can actually use a pointer to a float to put a floating point value in an integer variable. Just don't expect to be able to look at the variable x and get anything meaningful.
Reply:first of all float pointer can't hold address of integer variable so its no question about storing value any way

imperial

No comments:

Post a Comment