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).
Lets say we have 2 data structures:
struct ST1 {
char c1;
short s;
char c2;
double d;
int i;
};
In memory it will be:
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 |
But we can rearrange it, to make this data fit into machine word. Like this:
struct ST2 {
double d;
int i;
short s;
char c1;
char c2;
};
In this case for both 32 and 64 bit it will be represented at the same way (16 bytes):
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|
I have a couple of questions:
- It's like wild guess but main rule for
structis to define variables with bigger size at the beginning? - As I understand it's not working with stand-alone variables. Like
char str[] = "Hello";? - Padding byte, what code it has? Is it somewhere at ASCII table? Sorry, couldn't find it.
- 2 structures with all members represented at memory by different addresses and they can be placed not sequentially at memory?
- Such structure:
struct ST3 { char c1; char c2; char c3;} st3;Hassize = 3, 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?