题目:
下面程序结果是多少?
(一)
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>
using namespace std;
int main(){
float a=1.0f;
cout<<(int)a<<endl;
cout<<&a<<endl;
cout<<(int &)a<<endl;//输出1065353216,(int&)a相当于将该浮点数地址开始的sizeof(int)个字节当成int数据输出
cout<<boolalpha<<((int)a==(int &)a)<<endl;
float b=0.0f;
cout<<(int)b<<endl;
cout<<&b<<endl;
cout<<(int &)b<<endl;
cout<<boolalpha<<((int)b==(int &)b)<<endl;
return 0;
}
解析:该题实质上是考察了数据在内存中的
存储方式以及
数据的表示,是计算机组成原理中的内容
该题核心主要是对(int &)a的理解:
对于(int )a:这一点大家都知道,就是a的值强制转化成int型值,考察的是存储方式的内容
对于(int &)a:将a的引用强制转化成整型,意思是a所在的内存本来定义的时候为float类型,初始化为1.0f,但现在要按int类型解释这段程序,相当于*(int *)&a(将a的地址强制转化成int型指针,再取其内容)
(二)
#include <stdio.h>
int main(){
unsigned int a=0xfffffff7;
unsigned char i=(unsigned char)a;
char *b=(char*)&a;
printf("%08x, %08x",i,*b);
return 0;
}
第一个数i不用说了,char *b=(char *)&a其意思就是将一个unsigned int型的指针强制转化成一个char型的指针,只是指针的转化,影响的是指针的寻址,我们知道一个unsigned int型指针指向的地方寻址范围是从这个指针地址开始向后sizeof(unsigned int)=4字节,所以当转化成char型指针后,其寻址范围是从此地址开始向后sizeof(char)=1字节,运行一下下面的程序就会明白了
#include <stdio.h>
int main(){
unsigned int a=0xfffffff7;
unsigned char i=(unsigned char)a;
unsigned int *p=&a;
char *b=(char*)p;
printf("%08x, %08x",(++p),(++b));
return 0;
}