结构体知识点:
结构体就是把不同的数据类型整合起来成为一个自定义的数据类型。
1. 结构体声明
struct student 即我们创建的结构体,写在main函数外。struct为关键字,声明一个叫student的结构体,其中包括int型的id,一个char型的数组name[10],一个char型的gender.
struct student
{
int id;
char name[10];
char gender;
};
2. 结构体赋值
2.1 直接对创建的结构体类型变量std1进行赋值并输出结果。用结构体变量.属性进行访问。
struct student std1 = { 1, "Jinna", 'F'};
printf("%d %s %c\n",std1.id, std1.name, std1.gender);
2.2 创建结构体变量,然后进行访问赋值。注意:当字符串类型赋值时,不可直接复制,用strcpy。
struct student std2 ;
std2.id = 2;
strcpy(std2.name, "Jillian");
std2.gender = 'F';
printf("%d %s %c\n",std2.id, std2.name, std2.gender);
2.3 创建结构体的缩写
typedef struct student stst;
3. 结构体数组: 结构体类型 数组名【元素数量】
一个数组里面有几个结构体变量, 对其进行访问需要用for循环。
stst stdn[2] = {{ 4, "Jiu", 'M'}, {5, "Jenny", 'F'}};
int i;
for(i = 0 ; i < sizeof(stdn) /sizeof(stdn[0]) ; i ++)
{
printf("%d %s %c\n",stdn[i].id, stdn[i].name, stdn[i].gender);
}
4. 结构体指针 : 结构体类型 * 指针名 ->
一个存放结构体的指针,用malloc进行分配内存。定义时前后数据类型一致,均为定义的结构体类型。 对结构数组中成员进行访问采用 -> 访问。同样字符串也要用strcpy。
stst *pst = (stst *)malloc(sizeof(stst) * 1 );
pst->id = 6;
pst->gender = 'F';
strcpy(pst->name, "Jasmine");
printf("%d %s %c\n",pst->id, pst->name, pst->gender);
5.结构体指针数组
stst *pt[10] = {0};
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student
{
int id;
char name[10];
char gender;
};
typedef struct student stst ;
int main ()
{
struct student std1 = { 1, "Jinna", 'F'};
printf("%d %s %c\n",std1.id, std1.name, std1.gender);
struct student std2 ;
std2.id = 2;
strcpy(std2.name, "Jillian");
std2.gender = 'F';
printf("%d %s %c\n",std2.id, std2.name, std2.gender);
stst std3 = { 3, "June", 'M'};
printf("%d %s %c\n",std3.id, std3.name, std3.gender);
stst stdn[2] = {{ 4, "Jiu", 'M'}, {5, "Jenny", 'F'}};
int i;
for(i = 0 ; i < sizeof(stdn) /sizeof(stdn[0]) ; i ++)
{
printf("%d %s %c\n",stdn[i].id, stdn[i].name, stdn[i].gender);
}
stst *pst = (stst *)malloc(sizeof(stst) * 1 );
pst->id = 6;
pst->gender = 'F';
strcpy(pst->name, "Jasmine");
printf("%d %s %c\n",pst->id, pst->name, pst->gender);
stst *ptarray[2] = {0};
return 0;
}
结构体占用内存:
1. 结构体总长度等于最长成员长度的整数倍
2. 偏移量等于该成员长度的整数倍
结构体中若包含数组,则将数组每个元素拆开看。
若结构体中嵌套结构体,则也将结构体拆开看偏移量及长度。但要确保内部的结构体长度时内部结构体最长成员的整数倍。
struct insert{ // a 1 /4+ b 4 = 8/ c 1= 9/ 16 + d8 = 24/ 24 +2= 24/ + 2= 26/ 8的整数倍为32
int a;
float b;
char c;
double d; //8 bytes
short e;
};
struct group{ //char q 1 / 8 +8 long qa = 16/ +1 = 17/ 20 + 4= 24 / 24+ 4 = 28 / 28 + 1 = 29 / 32 + 8 = 42 / 42 + 2 = 44/ 8的整数倍为48
char q;
long qa;
char as;
struct insert a;
};