Struct:
/*************************************/
typedef struct
{
float price;
int ProductId;
char name[24];
} Laptop;
Laptop Laptop1, *Laptop2;
/*************************************/
Struct member
Laptop1. ProductId
对结构体元素取地址,不需要加括号 例如 &Laptop1. price 等效于 &(Laptop1. price)
pointer to a struct
Laptop2-> ProductId
(*Laptop2). ProductId
例子:
/*************************************/
struct test
{
char name[20];
int *ptr_mem;
uint y:5;
};
struct test t1;
/***********************************************/
Pointer in struct
t1.ptr_mem // 跟读取普通的member没区别
Array in struct
t1.name[i]; // 跟读取普通的member没区别
Bit field in struct
t1.y; // 跟读取普通的member没区别
nested struct Nested Structures in C - C Programming Tutorial - OverIQ.com
struct person
{
char name[20];
int age;
char dob[10];
};
struct student
{
struct person info;
int roll_no;
float marks;
}s1;
s1.info.name
Calculate the size of a structure, Struct padding Top 11 structure padding questions in C - Aticleworld
When you create the structure then compiler inserts some extra bytes between the members of structure for the alignment. These extra unused bytes are called padding bytes and this technique is called structure padding in C. A structure padding in C increases the performance of the processor at the penalty of memory
/*************************************/
typedef struct
{
int A;
char B;
char C;
} InfoData;
/*************************************/
sizeof(InfoData) = 12;
Difference between structure and union
The key difference between structure and union is that structure allocates enough space to store all the fields but unions only allocate enough space to store the largest field. In union, all fields are stored in the same space.
typedef uinon{
char a[4];
int b;
char c;
}room;
room room1;
union注意要点: 联合体(union)的使用方法及其本质_huqinwei的专栏-CSDN博客_联合体
- union所有元素的地址都是一样的,room1.b 跟 room1.c的地址一模一样,都是union的起始地址,虽然一个是int一个是char【用printf输出元素地址即可验证】
- 通过数组a可以对int b一个bytes一个byte的操作,通过int b可以直接对 数组char 4个bytes操作,但是要注意大小端
- union可以是struct的元素
常见面试问题
difference between union and structure
- difference between union and structure
- Can structures be passed to the functions by value? // you could, but passing by reference is a better idea
- Why cannot arrays be passed by values to functions? // you could, but passing by reference is a better idea
- How can you define a structure with bit field members?
- structure padding?
Reference: