Custom type
Structure
Basic knowledge of structure
- The difference between structure and array
- Create a structure
struct student //学生的数据类型
{
char name[10];
int age;
};
You can also create structure pointers and structure arrays
struct student* p; //结构体指针 ++跳过一整个结构体
struct student arr[10]; // 结构体数组 存放10个
- Structure access
Note:
#include<stdio.h>
struct student
{
char name[20];
int age;
}x,*p;
int main()
{
if (p == &x)
{
printf("haha");
}
return 0;
}
Here
p is different from &x. p is a structure pointer but it is a null pointer, which is equivalent to the following behavior
int a;
&x is a structure pointer that points to x after the address of x is saved with a structure pointer.
- The use of
typedef typedef can simplify a structure variable name
typedef struct book
{
char name[10];
int price;
} book;
int main()
{
book x[10] = {
0 };
return 0;
}
Now book is a structure type.
- Direct access to structure
typedef struct book
{
char name[10];
int price;
} book;
int main()
{
book x[10] = {
0 };
x[1].name[10] = "abcd"; //通过 点操作符访问
return 0;
}
- Indirect access via pointer
typedef struct
{
char name[10];
int price;
}book;
void fun(book* pc)
{
pc->price =10;
printf("%d",pc->price);
}
int main()
{
book x[10] = {
0 };
fun(x);
return 0;
}
Structure pointer
struct stu
{
char name[10];
int age;
};
int main()
{
struct stu *p;
return 0;
}
p is a pointer to a structure p+1 can jump to the next structure
*p+1 this is an illegal operation
*p and p *P is the entire structure p is a structure pointer
#include<stdio.h>
struct stu
{
char name[10];
int age;
}x;
int main()
{
struct stu *p=&x;
p->age = 10; // 可以这样 指针指向
(*p).age=10; // 可以解引用得到 x
return 0;
}
- Structure pointer access to nested structure
#include<stdio.h>
struct stu
{
int arr[2];
int age;
};
struct ptu
{
int a;
int b;
struct stu sr ;
}s;
int main()
{
struct ptu* p = &s;
p->sr.age;
return 0;
}
Structure memory allocation
First of all, what will this code output?
struct S1
{
char c1;
int i;
char c2;
};
int main()
{
printf("%d\n", sizeof(struct S1));
return 0;
}
Output 12 shouldn't be 1+4+1=6. It can be seen that the structure memory is stored differently.
12. 第一个成员在与结构体变量偏移量为0的地址处。
13. 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。
对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值。
VS中默认的值为8
Linux中的默认值为4
14. 结构体总大小为最大对齐数(每个成员变量都有一个对齐数)的整数倍。
15. 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍
16. 结构体的整体大小就是所 有最大对齐数(含嵌套结构体的对齐数)的整数倍。
Green char blue useless memory red int
joint
Poke here to unite