⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 align.html

📁 this is a mirrored site c-faq. thought might need offline
💻 HTML
字号:
<html><!-- Mirrored from c-faq.com/struct/align.html by HTTrack Website Copier/3.x [XR&CO'2008], Sat, 14 Mar 2009 08:02:57 GMT --><head><title>alignment and padding</title></head><body><p>[Someone asked me why it was that structures need internal paddding.This was my reply.]<p>From: scs@eskimo.com (Steve Summit)<br>Date: Sun, 17 Mar 2002 20:56:35 -0500<br>Message-Id: &lt;2002Mar17.2056.scs.007@aeroroot.scs.ndip.eskimo.net&gt;<p>You wrote:<br>&gt; ...what is still haunting my brain is why structures<br>&gt; need internal padding<p>It's for ``alignment''.  Many processors can't access 2- and4-byte quantities (e.g. ints and long ints) if they're crammedin every-which-way.<p>Suppose you have this structure:<p><pre>	struct	{		char a[3];		short int b;		long int c;		char d[3];		};</pre><p>Now, you might think that it ought to be possible to pack thisstructure into memory like this:<p><pre>	+-------+-------+-------+-------+	|           a           |   b   |	+-------+-------+-------+-------+	|   b   |           c           |	+-------+-------+-------+-------+	|   c   |           d           |	+-------+-------+-------+-------+</pre><p>But it's much, much easier on the processor if the compilerarranges it like this:<p><pre>	+-------+-------+-------+	|           a           |	+-------+-------+-------+	|       b       |	+-------+-------+-------+-------+	|               c               |	+-------+-------+-------+-------+	|           d           |	+-------+-------+-------+</pre><p>In the ``packed'' version, notice how it's at least a little bithard for you and me to see how the b and c fields wrap around?In a nutshell, it's hard for the processor, too.Therefore, most compilers will ``pad'' the structure(as if with extra, invisible fields)like this:<p><pre>	+-------+-------+-------+-------+	|           a           | pad1  |	+-------+-------+-------+-------+	|       b       |     pad2      |	+-------+-------+-------+-------+	|               c               |	+-------+-------+-------+-------+	|           d           | pad3  |	+-------+-------+-------+-------+</pre></body><!-- Mirrored from c-faq.com/struct/align.html by HTTrack Website Copier/3.x [XR&CO'2008], Sat, 14 Mar 2009 08:02:57 GMT --></html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -