Note that there are some explanatory texts on larger screens.

plurals
  1. POC: Data structures alignment
    text
    copied!<p>I'm working with structures and have several questions about them. As I understand structure variables will be placed at memory sequentially. Length of blocks(words) depends on machine architecture (32 bit - 4 byte, 64 bit - 8 bytes).</p> <p>Lets say we have 2 data structures:</p> <pre><code>struct ST1 { char c1; short s; char c2; double d; int i; }; </code></pre> <p>In memory it will be:</p> <pre><code>32 bit - 20 bytes 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | ------------------------------------------------------------------------------------------ c1| PB| s | s | c1| PB| PB| PB| d | d | d | d | d | d | d | d | i | i | i | i | 64 bit - 24 bytes | 20 | 21 | 22 | 23 | previous sequence + --------------------- | PB | PB | PB | PB | </code></pre> <p>But we can rearrange it, to make this data fit into machine word. Like this:</p> <pre><code>struct ST2 { double d; int i; short s; char c1; char c2; }; </code></pre> <p>In this case for both 32 and 64 bit it will be represented at the same way (16 bytes):</p> <pre><code> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | ---------------------------------------------------------------------- d | d | d | d | d | d | d | d | i | i | i | i | s | s | ch1| ch2| </code></pre> <p>I have a couple of questions:</p> <ul> <li>It's like wild guess but main rule for <code>struct</code> is to define variables with bigger size at the beginning?</li> <li>As I understand it's not working with stand-alone variables. Like <code>char str[] = "Hello";</code>?</li> <li>Padding byte, what code it has? Is it somewhere at ASCII table? Sorry, couldn't find it.</li> <li>2 structures with all members represented at memory by different addresses and they can be placed not sequentially at memory?</li> <li>Such structure: <code>struct ST3 { char c1; char c2; char c3;} st3;</code> Has <code>size = 3</code>, I understand that if we will add a member with other type into it, it will be aligned. But why it's not aligned before it?</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload