I. Structure (struct)
Create a struct data type declaration, different types of objects may be aggregated into a single object.
The compiler maintains byte for each structure type information, indicating the offset of each field. These offsets using the displacement as a memory reference instruction, thereby generating a reference to the structural elements.
Selecting a configuration of each field is handled entirely at compile time, the machine code does not contain information about the field declaration or containing column names .
Structure can be nested structure, as in the structure can be nested arrays, arrays can be nested in the array.
struct prob{ int * p; struct{ int x; int y; }s; struct prob *next; }
Field offset: p: 0 sx: 8 sy: 12 next: 16
II. Joint (union)
Different fields to reference the same memory block, a plurality of types to refer to the same object
Union the same syntax, but completely different semantics
Application: to know in advance of a data structure using two different fields are mutually exclusive , it can be declared as part of the two fields combined.
E.g:
Implement a binary tree data structure, satisfy:
Each leaf node has two data values of type double
Each node has a pointer to the internal nodes of two children, but no data
Can be a node in the manner the following statement
union node_u{ struct{ union node_u *left; union node_u *right; } internal; double data[2]; }; // 16bytes
Cons: no way to determine whether a given node is a leaf node or nodes
Improve:
Introducing different options enumerated type defined in the joint, and then create a structure comprising a tag field and this joint
typedef num{N_LEAF, N_INTERNAL} nodetype_t; struct node_t{ nodetype_t type; union{ struct{ struct node_t* left; struct node_t* right; }internal; double data[2]; }info; }; // 24bytes
For less field code, the above embodiment only two fields, the complexity of the code with respect to a result, savings are used in combination brings little.
For the data structure more fields , joint savings that would be more attractive.
Note: The byte order problem
III. Data Alignment
Alignment principle: base object address any byte K must be a multiple of K
Suppose a processor always takes 8 bytes from memory, then the address must be a multiple of 8
Benefits: simplify the hardware design of the interface between the processor and memory to improve the performance of the memory system
To ensure that each data type as specified way to organize and distribute the object for each data type are met.