用户操作
[留言]  [发消息]  [加为好友] 
订阅我的博客
XML聚合    FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
crystal521的公告
<p><center><FONT style="FONT-SIZE: 10pt; FILTER: shadow(color=#6495ED,strength=5); WIDTH: 100%; COLOR: #ffffff; LINE-HEIGHT: 100%" face=宋体 size=0> i find the great thing in this world is not so much where we stand as in what directiong we are moving ,to reach the port of the heaven ,we must sail sometimes with the wind ,and sometimes against it ,but we must sail ,not drift nor lie at anchor.</FONT></p> <DIV id=Layer1 style="Z-INDEX: 1; LEFT: 303px; WIDTH: 415px; POSITION: absolute; TOP: 60px; HEIGHT: 299px">    <OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0 height=400 width=400 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000><PARAM NAME="_cx" VALUE="10583"><PARAM NAME="_cy" VALUE="10583"><PARAM NAME="FlashVars" VALUE=""><PARAM NAME="Movie" VALUE="http://bbs.leadbbs.com/images/upload/2003/10/03/160034.swf"><PARAM NAME="Src" VALUE="http://bbs.leadbbs.com/images/upload/2003/10/03/160034.swf"><PARAM NAME="WMode" VALUE="Transparent"><PARAM NAME="Play" VALUE="-1"><PARAM NAME="Loop" VALUE="-1"><PARAM NAME="Quality" VALUE="High"><PARAM NAME="SAlign" VALUE=""><PARAM NAME="Menu" VALUE="0"><PARAM NAME="Base" VALUE=""><PARAM NAME="AllowScriptAccess" VALUE="always"><PARAM NAME="Scale" VALUE="ShowAll"><PARAM NAME="DeviceFont" VALUE="0"><PARAM NAME="EmbedMovie" VALUE="0"><PARAM NAME="BGColor" VALUE=""><PARAM NAME="SWRemote" VALUE=""><PARAM NAME="MovieData" VALUE=""><PARAM NAME="SeamlessTabbing" VALUE="1"> <embed src="http://bbs.jojin.com/images/upload/2003/10/03/160034.swf" width="400" height="400" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false" wmode="transparent"></embed></OBJECT> </div> <!-- Blog日历表开始 --> <script language="javascript"> var diarydays="<2004-08-05><2004-08-09><2004-08-12><2004-08-17><2004-08-19><2004-07-14><2004-07-13><2004-07-08><2004-07-05><2004-07-04><2004-07-03><2004-06-27><2004-06-26><2004-06-25>"; </script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <style> .calendarBigBorder { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; text-decoration: none; width: 170; background-color: #FFFFFF; font-size: 9pt;border:1px dotted #999; } .calendarTd { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; color: #000000; background-color: #eeeeee; height: 18px; width: 11%; text-align: center;} .calendarMInput { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; text-decoration: none; background-color: #FFFFFF; height: 15px; border: 1px solid #666666; width: 19px; color: #0099FF;} .calendarYInput { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; color: #0099FF; text-decoration: none; background-color: #FFFFFF; height: 15px; width: 34px; border: 1px solid #666666;} .calendarMonthTitle { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; font-weight: normal; height: 24px; text-align: center; color: #333333; text-decoration: none; background-color: #eeeeee; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-bottom-style: none; border-top-color: #999999; border-right-color: #999999; border-bottom-color: #999999; border-left-color: #999999;} .calendarNow { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; font-weight: bold; color: #000000; background-color: #C0C9D3; height: 18px; text-align: center;} .calendarDaySat { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; color: #333333; text-decoration: none; background-color: #eeeeee; text-align: center; height: 18px; width: 12%;} .calendarDaySun { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; color: #333333; text-decoration: none; background-color: #eeeeee; text-align: center; height: 18px; width: 12%;} .calendarLink { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; font-weight: normal; color: #333333; text-decoration: none; background-color: #E7E7F6; text-align: center; height: 18px;} .categoryTxt { font-family: "Arial", "Helvetica", "sans-serif", "宋体"; font-size: 9pt; line-height: 23px; color: #333333; text-decoration: none;} .categoryTable { border-right-width: 1px; border-bottom-width: 1px; border-right-style: solid; border-bottom-style: solid; border-left-style: none; border-right-color: #000000; border-bottom-color: #000000; border-top-width: 1px; border-top-style: solid; border-top-color: #71b99c;} </style> <SCRIPT LANGUAGE="JavaScript"> var months = new Array("一", "二", "三","四", "五", "六", "七", "八", "九","十", "十一", "十二"); var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30, 31); var days = new Array("日","一", "二", "三","四", "五", "六"); var classTemp; var calendarHover="calendarHover"; var today=new getToday(); var year=today.year; var month=today.month; var newCal; //得到某月天数 function getDays(month, year) { if (1 == month) return ((0 == year % 4) && (0 != (year % 100))) ||(0 == year % 400) ? 29 : 28; else return daysInMonth[month]; } //得到当天时间信息 function getToday() { this.now = new Date(); this.year = this.now.getFullYear(); this.month = this.now.getMonth(); this.day = this.now.getDate(); } //生成日历 function Calendar() { newCal = new Date(year,month,1); //当前月的第一天 today = new getToday(); var day = -1; //用来判断日历中是否为当天 var startDay = newCal.getDay(); //当月开始时间 var endDay=getDays(newCal.getMonth(), newCal.getFullYear());//当月结束时间 var daily = 0; //用来生成日历中的天数值 if ((today.year == newCal.getFullYear()) &&(today.month == newCal.getMonth())) day = today.day; var caltable = document.all.caltable.tBodies.calendar; //得到日历表格的集合 var intDaysInMonth =getDays(newCal.getMonth(), newCal.getFullYear()); //得到当月天数 //生成日历 for (var intWeek = 0; intWeek < caltable.rows.length;intWeek++) for (var intDay = 0;intDay < caltable.rows[intWeek].cells.length;intDay++) { var cell = caltable.rows[intWeek].cells[intDay]; //得到单元袼 //生成字符串用于判断当天是否有日志 var montemp=(newCal.getMonth()+1)<10?("0"+(newCal.getMonth()+1)):(newCal.getMonth()+1); if ((intDay == startDay) && (0 == daily)){ daily = 1;} var daytemp=daily<10?("0"+daily):(daily); var d="<"+newCal.getFullYear()+"-"+montemp+"-"+daytemp+">"; //选择样式 if(day==daily) cell.className="calendarNow"; else if(diarydays.indexOf(d)!=-1) cell.className="calendarLink"; else if(intDay==6) cell.className = "calendarDaySat"; else if (intDay==0) cell.className ="calendarDaySun"; else cell.className="calendarTd"; //生成值 if ((daily > 0) && (daily <= intDaysInMonth)) { cell.innerText = daily; daily++; } else cell.innerText = ""; } document.all.year.value=year; document.all.month.value=month+1; } function subMonth() { if ((month-1)<0) { month=11; year=year-1; } else { month=month-1; } Calendar(); } function addMonth() { if((month+1)>11) { month=0; year=year+1; } else { month=month+1; } Calendar(); } //得到响应事件 function getDiary() { var mon=(newCal.getMonth()+1)<10?("0"+(newCal.getMonth()+1)):(newCal.getMonth()+1); var day=event.srcElement.innerText<10?("0"+event.srcElement.innerText):(event.srcElement.innerText); var d="<"+newCal.getFullYear()+"-"+mon+"-"+day+">"; if ("TD" == event.srcElement.tagName) if (("" != event.srcElement.innerText)&&(diarydays.indexOf(d)!=-1)) { diary.location="/foxmail/archive/"+newCal.getFullYear()+"/"+mon+"/"+day+".aspx"; window.location.href = diary.location; } } function setDate() { if (document.all.month.value<1||document.all.month.value>12) { alert("月的有效范围在1-12之间!"); return; } year=Math.ceil(document.all.year.value); month=Math.ceil(document.all.month.value-1); Calendar(); } </SCRIPT> <table border="0" cellpadding="0" cellspacing="1" class="calendarBigBorder" id="caltable" width="200"> <thead> <tr align="center" valign="middle"> <td colspan="7" class="calendarMonthTitle"> <input name="year" type="text" class="calendarYInput" size="3" maxlength="4" onkeydown="if (event.keyCode==13){setDate()}" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onpaste="this.value=this.value.replace(/[^0-9]/g,'')">年 <input name="month" type="text" class="calendarMInput" size="1" maxlength="2" onkeydown="if (event.keyCode==13){setDate()}" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onpaste="this.value=this.value.replace(/[^0-9]/g,'')">月 [<a onClick="addMonth()" href="javascript :;">下月</a>] [<a onClick="subMonth()" href="javascript :;">上月</a>]</td> </tr> <tr align="center" valign="middle"> <SCRIPT LANGUAGE="JavaScript"> document.write("<TD class=calendarDaySun id=diary>" + days[0] + "</TD>"); for (var intLoop = 1; intLoop < days.length-1; intLoop++) document.write("<TD class=calendarTd id=diary>" + days[intLoop] + "</TD>"); document.write("<TD class=calendarDaySat id=diary>" + days[intLoop] + "</TD>"); </SCRIPT> </TR> </thead> <TBODY border=1 cellspacing="0" cellpadding="0" ID="calendar" ALIGN=CENTER ONCLICK="getDiary()" onmouseup=document.selection.empty() oncontextmenu="return false" onselectstart="return false" ondragstart="return false" onbeforecopy="return false" oncopy=document.selection.empty() onselect=document.selection.empty()> <SCRIPT LANGUAGE="JavaScript"> for (var intWeeks = 0; intWeeks < 6; intWeeks++) { document.write("<TR style='cursor:hand'>"); for (var intDays = 0; intDays < days.length;intDays++) document.write("<TD class=calendarTd onMouseover='{classTemp=this.className;this.className=calendarHover}' onMouseOut='this.className=classTemp'></TD>"); document.write("</TR>"); } </SCRIPT> </tbody> </table> <script LANGUAGE="JavaScript"> Calendar(); </script> <!-- Blog日历表结束 --> <h3>直接页面点击</h3> <img src=http://nmc2.jy.js.cn/cgi-bin/counter.pl?id=crystal521&md=a48&ln=10&from=2000&bd=$0;$0;$0>
文章分类
驱动开发链接
心情小驿站
存档

转载  struct详解 收藏

1. struct的巨大作用
  在网络协议、通信控制、嵌入式系统的C/C++编程中,我们经常要传送的不是简单的字节流(char型数组),而是多种数据组合起来的一个整体,其表现形式是一个结构体。


  经验不足的开发人员往往将所有需要传送的内容依顺序保存在char型数组中,通过指针偏移的方法传送网络报文等信息。这样做编程复杂,易出错,而且一旦控制方式及通信协议有所变化,程序就要进行非常细致的修改。


  一个有经验的开发者则灵活运用结构体,举一个例子,假设网络或控制协议中需要传送三种报文,其格式分别为packetA、packetB、packetC:


struct structA
{
int a;
char b;
};


struct structB
{
char a;
short b;
};


struct structC
{
int a;
char b;
float c;
}
  优秀的程序设计者这样设计传送的报文:


struct CommuPacket
{
int iPacketType;  //报文类型标志
union      //每次传送的是三种报文中的一种,使用union
{
  struct structA packetA;
  struct structB packetB;
  struct structC packetC;
}
};
  在进行报文传送时,直接传送struct CommuPacket一个整体。


  假设发送函数的原形如下:


// pSendData:发送字节流的首地址,iLen:要发送的长度
Send(char * pSendData, unsigned int  iLen);
发送方可以直接进行如下调用发送struct CommuPacket的一个实例sendCommuPacket:
Send( (char *)&sendCommuPacket , sizeof(CommuPacket) );
假设接收函数的原形如下:
// pRecvData:发送字节流的首地址,iLen:要接收的长度
//返回值:实际接收到的字节数
unsigned int Recv(char * pRecvData, unsigned int  iLen);
  接收方可以直接进行如下调用将接收到的数据保存在struct CommuPacket的一个实例
recvCommuPacket中:


Recv( (char *)&recvCommuPacket , sizeof(CommuPacket) );
  接着判断报文类型进行相应处理:


switch(recvCommuPacket. iPacketType)
{
    case PACKET_A:
    …    //A类报文处理
    break;
    case PACKET_B:
    …   //B类报文处理
    break;
    case PACKET_C:
    …   //C类报文处理
    break;
}
  以上程序中最值得注意的是


Send( (char *)&sendCommuPacket , sizeof(CommuPacket) );
Recv( (char *)&recvCommuPacket , sizeof(CommuPacket) );
  中的强制类型转换:(char *)&sendCommuPacket、(char *)&recvCommuPacket,先取地址,再转化为char型指针,这样就可以直接利用处理字节流的函数。


  利用这种强制类型转化,我们还可以方便程序的编写,例如要对sendCommuPacket所处内存初始化为0,可以这样调用标准库函数memset():


memset((char *)&sendCommuPacket,0, sizeof(CommuPacket));


2. struct的成员对齐
  Intel、微软等公司曾经出过一道类似的面试题:


1. #i nclude <iostream.h>


2. #pragma pack(8)
3. struct example1
4. {
5. short a;
6. long b;
7. };


8. struct example2
9. {
10. char c;
11. example1 struct1;
12. short e;   
13. };
14. #pragma pack()


15. int main(int argc, char* argv[])
16. {
17. example2 struct2;


18. cout << sizeof(example1) << endl;
19. cout << sizeof(example2) << endl;
20. cout << (unsigned int)(&struct2.struct1) - (unsigned int)(&struct2)
<< endl;


21. return 0;
22. }
  问程序的输入结果是什么?


  答案是:


8
16
4


  不明白?还是不明白?下面一一道来:


2.1 自然对界


  struct是一种复合数据类型,其构成元素既可以是基本数据类型(如int、long、float等)的变量,也可以是一些复合数据类型(如array、struct、union等)的数据单元。对于结构体,编译器会自动进行成员变量的对齐,以提高运算效率。缺省情况下,编译器为结构体的每个成员按其自然对界(natural alignment)条件分配空间。各个成员按照它们被声明的顺序在内存中顺序存储,第一个成员的地址和整个结构的地址相同。


  自然对界(natural alignment)即默认对齐方式,是指按结构体的成员中size最大的成员对齐。


  例如:


struct naturalalign
{
char a;
short b;
char c;
};
  在上述结构体中,size最大的是short,其长度为2字节,因而结构体中的char成员a、c都以2为单位对齐,sizeof(naturalalign)的结果等于6;


  如果改为:


struct naturalalign
{
char a;
int b;
char c;
};
  其结果显然为12。


2.2指定对界


  一般地,可以通过下面的方法来改变缺省的对界条件:


  · 使用伪指令#pragma pack (n),编译器将按照n个字节对齐;
  · 使用伪指令#pragma pack (),取消自定义字节对齐方式。


  注意:如果#pragma pack (n)中指定的n大于结构体中最大成员的size,则其不起作用,结构体仍然按照size最大的成员进行对界。


  例如:


#pragma pack (n)
struct naturalalign
{
char a;
int b;
char c;
};
#pragma pack ()
  当n为4、8、16时,其对齐方式均一样,sizeof(naturalalign)的结果都等于12。而当n为2时,其发挥了作用,使得sizeof(naturalalign)的结果为8。


  在VC++ 6.0编译器中,我们可以指定其对界方式,其操作方式为依次选择projetct >setting > C/C++菜单,在struct member alignment中指定你要的对界方式。

                                   图1:在VC++ 6.0中指定对界方式

  另外,通过__attribute((aligned (n)))也可以让所作用的结构体成员对齐在n字节边界上,但是它较少被使用,因而不作详细讲解。


2.3 面试题的解答


  至此,我们可以对Intel、微软的面试题进行全面的解答。


  程序中第2行#pragma pack (8)虽然指定了对界为8,但是由于struct example1中的成员最大size为4(long变量size为4),故struct example1仍然按4字节对界,struct example1的size为8,即第18行的输出结果;


  struct example2中包含了struct example1,其本身包含的简单数据成员的最大size为2(short变量e),但是因为其包含了struct example1,而struct example1中的最大成员size为4,struct example2也应以4对界,#pragma pack (8)中指定的对界对struct example2也不起作用,故19行的输出结果为16;


  由于struct example2中的成员以4为单位对界,故其char变量c后应补充3个空,其后才是成员struct1的内存空间,20行的输出结果为4。



3. C和C++间struct的深层区别
  在C++语言中struct具有了“类” 的功能,其与关键字class的区别在于struct中成员变量和函数的默认访问权限为public,而class的为private。


  例如,定义struct类和class类:


struct structA
{
char a;

}
class classB
{
      char a;
      …
}
  则:


struct A a;
a.a = 'a';    //访问public成员,合法
classB b;
b.a = 'a';    //访问private成员,不合法
  许多文献写到这里就认为已经给出了C++中struct和class的全部区别,实则不然,另外一点需要注意的是:


  C++中的struct保持了对C中struct的全面兼容(这符合C++的初衷——“a better c”),因而,下面的操作是合法的:


//定义struct
struct structA
{
char a;
char b;
int c;
};
structA a = {'a' , 'a' ,1};    //  定义时直接赋初值
  即struct可以在定义的时候直接以{ }对其成员变量赋初值,而class则不能,在经典书目《thinking C++ 2nd edition》中作者对此点进行了强调。


4. struct编程注意事项
  看看下面的程序:


1. #i nclude <iostream.h>


2. struct structA
3. {
4. int iMember;
5. char *cMember;
6. };


7. int main(int argc, char* argv[])
8. {
9. structA instant1,instant2;
10.char c = 'a';
   
11. instant1.iMember = 1;
12. instant1.cMember = &c;


13.instant2 = instant1;


14.cout << *(instant1.cMember) << endl;


15.*(instant2.cMember) = 'b';


16. cout << *(instant1.cMember) << endl;


17. return 0;
}
  14行的输出结果是:a
  16行的输出结果是:b


  Why?我们在15行对instant2的修改改变了instant1中成员的值!


  原因在于13行的instant2 = instant1赋值语句采用的是变量逐个拷贝,这使得instant1和instant2中的cMember指向了同一片内存,因而对instant2的修改也是对instant1的修改。


  在C语言中,当结构体中存在指针型成员时,一定要注意在采用赋值语句时是否将2个实例中的指针型成员指向了同一片内存。


  在C++语言中,当结构体中存在指针型成员时,我们需要重写struct的拷贝构造函数并进行“=”操作符重载。

 

发表于 @ 2007年03月16日 22:00:00 | 评论( loading... ) | 编辑| 举报| 收藏

旧一篇:C/C++笔试题(3) | 新一篇:VC++6.0编译环境介绍

  • 发表评论
  • 评论内容:
  •  
Copyright © crystal521
Powered by CSDN Blog