C语言你不可以错过的8个经典题目

发表于:2017-4-11 09:39

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Dawn_sf    来源:CSDN

  现在我说的对不对呢? 大家看看输出结果
  6.在x86,vc++ 6.0环境下,有下列程序
<span style="font-family:KaiTi_GB2312;font-size:14px;">#include<stdio.h>
#include<Windows.h>
int main()
{
char c;
unsigned char uc;
unsigned short us;
c = 128;
uc = 128;
us = c + uc;
printf("0x%x\n", us);
us = (unsigned char)c + uc;
printf("0x%x\n", us);
us = c + (char)uc;
printf("0x%x\n", us);
system("pause");
return 0;
}
</span>
  做这道题前应该知道 char 的取值范围是-128 ~ 127,所以当你给uc赋128的时候,它真实的值为-128.
  具体我说的对不对? 看看运行结果。
  7.
<span style="font-family:KaiTi_GB2312;font-size:14px;">#include<stdio.h>
#include<Windows.h>
struct tagAAA
{
unsigned char ucld : 1;
unsigned char ucpara : 2;
unsigned char ucState : 6;
unsigned char ucTail : 4;
unsigned char ucAvail;
unsigned char ucTail2;
unsigned char ucData;
}AAA_S1;
struct tagAAA2
{
unsigned int ucld : 1;
unsigned int ucpara : 2;
unsigned int ucState : 6;
unsigned int ucTail : 4;
unsigned int ucAvail;
unsigned int ucTail2;
unsigned int ucData;
}AAA_S2;
int main()
{
printf("%d  %d\n", sizeof(AAA_S1), sizeof(AAA_S2));
system("pause");
return 0;
}
</span>
  求AAA_S再分别为1字节对齐和四字节对齐的情况下,占用空间的大小:?
  答案为 6 16.
  这个问题就是位域的问题,我有专门关于结构体对齐的博客,不懂可以过去看一看。
  8.
<span style="font-family:KaiTi_GB2312;font-size:14px;">#include<stdio.h>
#include<Windows.h>
#pragma pack(4);
int main()
{
unsigned char puc[4];
struct sagPIM{
unsigned char ucpim1;
unsigned char ucDate:1;
unsigned char ucDate1:2;
unsigned char ucDate2:3;
}*pstPimData;
pstPimData = (struct sagPIM*)puc;
memset(puc, 0, 4);
pstPimData->ucpim1 = 2;
pstPimData->ucDate = 3;
pstPimData->ucDate1 = 4;
pstPimData->ucDate2 = 5;
printf("%02x  %02x  %02x  %02x\n", puc[0], puc[1], puc[2], puc[3]);
system("pause");
return 0;
}
</span>
  这个主要还是位域,还有存储的一些关系了。
  因为按照位域存储,该结构体只需要2个字节即可存储全部内容,然后开始思考他内部的结构。
  下来我画一个图理解一下。
  再看看运行的结果吧 有图有真相。
  这些题目都很经典,可以帮助我们理解一些藏在深处的知识,各种坑各种容易犯的错误。。
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号