Forced conversion of pointer type, forced pointer type

Source: Internet
Author: User

Forced conversion of pointer type, forced pointer type

The problem is:

# Include <iostream. h>
Void main (){
Int k = 1;
Int * f = & k;
* (Float *) (f) = 1;
Cout <* f;
} // Why is the output not 1?


At this time, we can see that there is format conversion in the function Format. If there are two or more formats in addition to the void format during format conversion, in this case, the memory occupied by the variable indicated by the pointer changes accordingly.


For this question:


When you forcibly change the int pointer to the float pointer, the data actually goes beyond the memory space range defined by the int.


For example, int occupies 4 bytes, float occupies 8 bytes, and k = 1 is stored in 4 bytes.
When you convert the pointer to float, it will read the four bytes of 1 and the additional four bytes following it, so it is definitely not 1. What should be random?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.