3.9 heterogeneous data structures
C
Language provides two kinds of the combination of different types of objects to create mechanisms for data types together:
structure ( structure
), with the keyword struct
to declare the collection of multiple objects into one unit;
joint ( union
), with key sub union
to declare that allows several different types of references to an object.
3.9.1 Structure
C
Language struct
statement creates a data type, the object may be aggregated into a different type of object. By name to refer to the various components of the structure.
Example:
In addition, we can both declare the variable and initialize it means in a statement:
struct rect r = {0, 0, 10, 20, 0xFF00FF};
Returning to the example of the rectangular area:
long area(struct rect *rp)
{
return (*rp).width * (*rp).height;
}
rp -> width
It is equivalent to (*rp).width
.
Example:
struct rec {
int i;
int j;
int a[2];
int *p;
};
Example:
Registers: r in %rdi
r->j = r->i
movl (%rdi), %eax Get r->i
movl %eax, 4(%rdi) Store in r->j
Registers: r in %rdi, i in %rsi
&(r->a[i])
leaq 8(%rdi, %rsi, 4), %rax Set %rax to &r->a[i]
Registers: r in %rdi
r->p = &r->a[r->i + r->j ];
movl 4(%rdi), %eax Get r->j
addl (%rdi), %eax Add r->i
cltq Extend to 8 bytes
leaq 8(%rdi, %rax, 4), %rax Compute &r->a[r->i + r->j]
movq %rax, 16(%rdi) Store in r->p
3.9.2 Joint
Joint allows multiple types to refer to an object.
Consider the following statement:
struct S3
{
char c;
int i[2];
double v;
}
union U3
{
char c;
int i[2];
double v;
}
As can be seen the type union U3 *
of pointer p
, p->c
, p->i[0]
and p->v
the starting location reference is a data structure. A combined total size equal to the size of its largest fields .
3.9.3 Data Alignment
Many computer systems for basic data types legal address made some restrictions , require some type of object address must be some value K (usually 2
, 4
or 8
multiples). This alignment restriction simplifies the hardware design of the interface is formed between the processor and memory system.
K | Types of |
---|---|
1 | char |
2 | short |
4 | int, float |
8 | long, double,chat* |
For example, the jump table contains the following instructions compiled declaration:
.align 8
This ensures that the start address of the data following it is 8 multiples.
Example:
the blue part of the address space is filled aligned.