📄 c-c+语言struct深层探索 - asm, c, c++ are my all - c++博客.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0063)http://www.cppblog.com/jerysun0818/archive/2006/07/06/9508.html -->
<HTML><HEAD
id=Head><TITLE>C/C+语言struct深层探索 - asm, c, c++ are my all - C++博客</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META id=metaKeywords content=C/C+语言struct深层探索 name=keywords><LINK id=MainCss
href="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/style.css"
type=text/css rel=stylesheet><LINK id=RSSLink title=RSS
href="http://www.cppblog.com/jerysun0818/rss.aspx" type=application/rss+xml
rel=alternate>
<META content="MSHTML 6.00.2800.1106" name=GENERATOR></HEAD>
<BODY>
<FORM id=Form1 name=Form1 onsubmit="javascript:return WebForm_OnSubmit();"
action=9508.html method=post>
<DIV><INPUT id=__EVENTTARGET type=hidden name=__EVENTTARGET> <INPUT
id=__EVENTARGUMENT type=hidden name=__EVENTARGUMENT> <INPUT
id=" __VIEWSTATE" type=hidden name=__VIEWSTATE> </DIV>
<SCRIPT type=text/javascript>
<!--
var theForm = document.forms['Form1'];
if (!theForm) {
theForm = document.Form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
// -->
</SCRIPT>
<SCRIPT
src="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/WebResource.axd"
type=text/javascript></SCRIPT>
<SCRIPT language=JavaScript>
function ctlent(evt,id)
{
if(evt.ctrlKey && evt.keyCode == 13)
{
try
{
TempSave(id);
}
catch(ex)
{
}
finally
{
__doPostBack('AjaxHolder$PostComment$btnSubmit','')
}
}
}</SCRIPT>
<SCRIPT language=JavaScript>function SetReplyAuhor(author){document.getElementById('AjaxHolder_PostComment_tbComment').value+="@"+author+"\n";document.getElementById('AjaxHolder_PostComment_tbComment').focus();return false}</SCRIPT>
<SCRIPT
src="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/ScriptResource.axd"
type=text/javascript></SCRIPT>
<SCRIPT
src="E:\新建文件夹\C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files\ScriptResource(1).axd"
type=text/javascript></SCRIPT>
<SCRIPT
src="E:\新建文件夹\C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files\ScriptResource(2).axd"
type=text/javascript></SCRIPT>
<SCRIPT type=text/javascript>
<!--
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
return true;
}
// -->
</SCRIPT>
<!--done-->
<TABLE cellSpacing=0 cellPadding=0 width="100%" align=center border=0>
<TBODY>
<TR>
<TD width=299
background="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/banner1.jpg"></TD>
<TD
background="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/banner.jpg"><!--done-->
<DIV class=header>
<DIV class=headerText><A class=headermaintitle id=Header1_HeaderTitle
href="http://www.cppblog.com/jerysun0818/">asm, c, c++ are my
all</A><BR>-- Core In Computer </DIV></DIV></TD>
<TD width=296
background="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/banner2.jpg"></TD></TR></TBODY></TABLE>
<DIV id=mylinks><!--done--><A class=menu id=MyLinks1_HomeLink
href="http://www.cppblog.com/">C++博客</A> <A class=menu
id=MyLinks1_MyHomeLink
href="http://www.cppblog.com/jerysun0818/">首页</A> <A
class=menu id=MyLinks1_NewArticleLink
href="http://www.cppblog.com/EnterMyBlog.aspx?NewArticle=1">新文章</A>
<A class=menu id=MyLinks1_NewPostLink
href="http://www.cppblog.com/jerysun0818/admin/EditPosts.aspx?opt=1">新随笔</A>
<A class=menu id=MyLinks1_Syndication
href="http://www.cppblog.com/jerysun0818/Rss.aspx">聚合</A><A id=MyLinks1_XMLLink
href="http://www.cppblog.com/jerysun0818/Rss.aspx"><IMG
style="BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px"
src="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/xml.gif"></A>
<A class=menu id=MyLinks1_Admin
href="http://www.cppblog.com/jerysun0818/admin/EditPosts.aspx">管理</A> <!-- <a id="MyLinks1_ContactLink" accesskey="9" class="menu" href="http://www.cppblog.com/jerysun0818/contact.aspx?id=1">联系</a> --></DIV>
<DIV id=mytopmenu>
<DIV id=mystats><!--done-->
<DIV class=blogStats>posts - 139, comments - 99, trackbacks - 0
</DIV></DIV></DIV>
<DIV id=centercontent><!--done-->
<DIV class=post>
<DIV class=postTitle><A class=postTitle2 id=viewpost1_TitleUrl
href="http://www.cppblog.com/jerysun0818/archive/2006/07/06/9508.html">C/C+语言struct深层探索</A>
</DIV>
<P><FONT size=2><FONT color=#800080 size=3><STRONG>C/C+语言struct深层探索</STRONG>
</FONT><BR></FONT><FONT size=2><BR>出处:PConline </FONT></P>
<P><FONT size=2>1.
struct的巨大作用<BR> 面对一个人的大型C/C++程序时,只看其对struct的使用情况我们就可以对其编写者的编程经验进行评估。因为一个大型的C/C++程序,势必要涉及一些(甚至大量)进行数据组合的结构体,这些结构体可以将原本意义属于一个整体的数据组合在一起。从某种程度上来说,会不会用struct,怎样用struct是区别一个开发人员是否具备丰富开发经历的标志。
</FONT></P>
<P><FONT
size=2> 在网络协议、通信控制、嵌入式系统的C/C++编程中,我们经常要传送的不是简单的字节流(char型数组),而是多种数据组合起来的一个整体,其表现形式是一个结构体。
</FONT></P>
<P><FONT
size=2> 经验不足的开发人员往往将所有需要传送的内容依顺序保存在char型数组中,通过指针偏移的方法传送网络报文等信息。这样做编程复杂,易出错,而且一旦控制方式及通信协议有所变化,程序就要进行非常细致的修改。
</FONT></P>
<P><FONT
size=2> 一个有经验的开发者则灵活运用结构体,举一个例子,假设网络或控制协议中需要传送三种报文,其格式分别为packetA、packetB、packetC:
</FONT></P>
<P><FONT size=2>struct structA <BR>{<BR>int a;<BR>char b;<BR>}; </FONT></P>
<P><FONT size=2>struct structB <BR>{<BR>char a;<BR>short b;<BR>}; </FONT></P>
<P><FONT size=2>struct structC<BR>{<BR>int a;<BR>char b;<BR>float
c;<BR>}<BR> 优秀的程序设计者这样设计传送的报文: </FONT></P>
<P><FONT size=2>struct CommuPacket<BR>{<BR>int
iPacketType; //报文类型标志<BR>union //每次传送的是三种报文中的一种,使用union<BR>{<BR>
struct structA packetA;<BR> struct structB packetB;<BR> struct
structC packetC;<BR>}<BR>};<BR> 在进行报文传送时,直接传送struct CommuPacket一个整体。
</FONT></P>
<P><FONT size=2> 假设发送函数的原形如下: </FONT></P>
<P><FONT size=2>// pSendData:发送字节流的首地址,iLen:要发送的长度<BR>Send(char * pSendData,
unsigned int iLen);<BR>发送方可以直接进行如下调用发送struct
CommuPacket的一个实例sendCommuPacket:<BR>Send( (char *)&sendCommuPacket ,
sizeof(CommuPacket) );<BR>假设接收函数的原形如下:<BR>//
pRecvData:发送字节流的首地址,iLen:要接收的长度<BR>//返回值:实际接收到的字节数<BR>unsigned int Recv(char *
pRecvData, unsigned int iLen);<BR> 接收方可以直接进行如下调用将接收到的数据保存在struct
CommuPacket的一个实例recvCommuPacket中: </FONT></P>
<P><FONT size=2>Recv( (char *)&recvCommuPacket , sizeof(CommuPacket)
);<BR> 接着判断报文类型进行相应处理: </FONT></P>
<P><FONT size=2>switch(recvCommuPacket. iPacketType)<BR>{<BR>
case PACKET_A:<BR> …
//A类报文处理<BR> break;<BR> case
PACKET_B:<BR> … //B类报文处理<BR>
break;<BR> case PACKET_C:<BR> …
//C类报文处理<BR> break;<BR>}<BR> 以上程序中最值得注意的是 </FONT></P>
<P><FONT size=2>Send( (char *)&sendCommuPacket , sizeof(CommuPacket)
);<BR>Recv( (char *)&recvCommuPacket , sizeof(CommuPacket)
);<BR> 中的强制类型转换:(char *)&sendCommuPacket、(char
*)&recvCommuPacket,先取地址,再转化为char型指针,这样就可以直接利用处理字节流的函数。 </FONT></P>
<P><FONT
size=2> 利用这种强制类型转化,我们还可以方便程序的编写,例如要对sendCommuPacket所处内存初始化为0,可以这样调用标准库函数memset():
</FONT></P>
<P><FONT size=2>memset((char *)&sendCommuPacket,0, sizeof(CommuPacket));
</FONT></P>
<P><FONT size=2>2. struct的成员对齐<BR> Intel、微软等公司曾经出过一道类似的面试题:<BR>1. #include
<iostream.h><BR>2. #pragma pack(8)<BR>3. struct example1<BR>4. {<BR>5.
short a;<BR>6. long b;<BR>7. };<BR>8. struct example2<BR>9. {<BR>10. char
c;<BR>11. example1 struct1;<BR>12. short e; <BR>13. };<BR>14.
#pragma pack()<BR>15. int main(int argc, char* argv[])<BR>16. {<BR>17. example2
struct2;<BR>18. cout << sizeof(example1) << endl;<BR>19. cout
<< sizeof(example2) << endl;<BR>20. cout << (unsigned
int)(&struct2.struct1) - (unsigned int)(&struct2) << endl;<BR>21.
return 0;<BR>22.
}<BR> 问程序的输入结果是什么?<BR> 答案是:<BR>8<BR>16<BR>4<BR> 不明白?还是不明白?下面一一道来:<BR>2.1
自然对界<BR> struct是一种复合数据类型,其构成元素既可以是基本数据类型(如int、long、float等)的变量,也可以是一些复合数据类型(如array、struct、union等)的数据单元。对于结构体,编译器会自动进行成员变量的对齐,以提高运算效率。缺省情况下,编译器为结构体的每个成员按其自然对界(natural
alignment)条件分配空间。各个成员按照它们被声明的顺序在内存中顺序存储,第一个成员的地址和整个结构的地址相同。<BR> 自然对界(natural
alignment)即默认对齐方式,是指按结构体的成员中size最大的成员对齐。<BR> 例如:<BR>struct
naturalalign<BR>{<BR>char a;<BR>short b;<BR>char
c;<BR>};<BR> 在上述结构体中,size最大的是short,其长度为2字节,因而结构体中的char成员a、c都以2为单位对齐,sizeof(naturalalign)的结果等于6;<BR> 如果改为:<BR>struct
naturalalign<BR>{<BR>char a;<BR>int b;<BR>char c;<BR>};<BR> 其结果显然为12。
</FONT></P>
<P><FONT size=2>2.2指定对界<BR> 一般地,可以通过下面的方法来改变缺省的对界条件:<BR> · 使用伪指令#pragma pack
(n),编译器将按照n个字节对齐;<BR> · 使用伪指令#pragma pack (),取消自定义字节对齐方式。<BR> 注意:如果#pragma
pack (n)中指定的n大于结构体中最大成员的size,则其不起作用,结构体仍然按照size最大的成员进行对界。<BR> 例如:<BR>#pragma
pack (n)<BR>struct naturalalign<BR>{<BR>char a;<BR>int b;<BR>char
c;<BR>};<BR>#pragma pack
()<BR> 当n为4、8、16时,其对齐方式均一样,sizeof(naturalalign)的结果都等于12。而当n为2时,其发挥了作用,使得sizeof(naturalalign)的结果为8。<BR> 在VC++
6.0编译器中,我们可以指定其对界方式,其操作方式为依次选择projetct > setting > C/C++菜单,在struct member
alignment中指定你要的对界方式。<BR> 另外,通过__attribute((aligned
(n)))也可以让所作用的结构体成员对齐在n字节边界上,但是它较少被使用,因而不作详细讲解。 </FONT></P>
<P><FONT size=2>2.3 面试题的解答<BR> 至此,我们可以对Intel、微软的面试题进行全面的解答。<BR> 程序中第2行#pragma
pack (8)虽然指定了对界为8,但是由于struct example1中的成员最大size为4(long变量size为4),故struct
example1仍然按4字节对界,struct example1的size为8,即第18行的输出结果;<BR> struct
example2中包含了struct example1,其本身包含的简单数据成员的最大size为2(short变量e),但是因为其包含了struct
example1,而struct example1中的最大成员size为4,struct example2也应以4对界,#pragma pack
(8)中指定的对界对struct example2也不起作用,故19行的输出结果为16;<BR> 由于struct
example2中的成员以4为单位对界,故其char变量c后应补充3个空,其后才是成员struct1的内存空间,20行的输出结果为4。</FONT> </P>
<DIV class=postDesc>posted on 2006-07-06 21:20 <A
href="http://www.cppblog.com/jerysun0818/">Jerry Cat</A> 阅读(33) <A
href="http://www.cppblog.com/jerysun0818/archive/2006/07/06/9508.html#Post">评论(0)</A>
<A
href="http://www.cppblog.com/jerysun0818/admin/EditPosts.aspx?postid=9508">编辑</A> <A
href="http://www.cppblog.com/jerysun0818/AddToFavorite.aspx?id=9508">收藏</A> <A
href="http://www.cppblog.com/jerysun0818/services/trackbacks/9508.aspx">引用</A>
</DIV></DIV><IMG height=1
src="C-C+语言struct深层探索 - asm, c, c++ are my all - C++博客.files/9508.jpg" width=1> <!--
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
<rdf:Description
rdf:about="http://www.cppblog.com/jerysun0818/archive/2006/07/06/9508.html"
dc:identifier="http://www.cppblog.com/jerysun0818/archive/2006/07/06/9508.html"
dc:title="C/C+语言struct深层探索"
trackback:ping="http://www.cppblog.com/jerysun0818/services/trackbacks/9508.aspx" />
</rdf:RDF>
-->
<SCRIPT type=text/javascript>
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('AjaxHolder$scriptmanager1', document.getElementById('Form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tAjaxHolder$UpdatePanel1'], [], [], 90);
//]]>
</SCRIPT>
<DIV id=AjaxHolder_UpdatePanel1>
<STYLE>TD {
FONT-SIZE: 12px
}
.commentTextBox {
FONT-SIZE: 13px; FONT-FAMILY: Verdana
}
</STYLE>
<!--Beging Temp Save-->
<STYLE>.userData {
BEHAVIOR: url(#default#userdata)
}
</STYLE>
<DIV class=userData id=CommentsPersistDiv></DIV>
<SCRIPT type=text/javascript>
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(handleInitializeRequest);
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleEndRequest);
}
function handleInitializeRequest(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
var eid = args.get_postBackElement().id;
if (eid.indexOf("DeleteLink")>0)
{
args.get_postBackElement().innerHTML = "<font color='red'>正在删除...</font>";
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -