C提高-DAY-5

DAY05

  1. 结构体的使用

1 结构体类型基本操作

1.1结构体类型定义

struct Stu{
	char name[32];
	char tile[32];
	int age;
	char addr[50];
};

/* 通过typedef把struct Stu改名为Stu */
typedef struct Stu{
	int a;
}Stu;

1.2 结构体变量的定义

/* 1.先定义类型,在定义变量,最常用 */
struct Stu a;
/* 2.定义类型的同时,定义变量 */
struct _Stu{
	char name[32];
	char tile[32];
	int age;
	char addr[50];
}c;

struct{
	char name[32];
	char tile[32];
	int age;
	char addr[50];
}e, f;

1.3 结构体变量初始化

/* 定义变量同时初始化 */
struct Stu g = {"lily", "teacher", 22, "guangzhou"};

1.4 变量和指针法操作结构体成员

/* 变量法, 点运算符 */
struct Stu h;
strcpy(h.name, "^_^");
(&h)->name;

/* 指针法, -> */
struct Stu *p;
p = &h;
strcpy(p->name, "abc");
(*p).name

1.5 结构体数组

/* 结构体类型 */
typedef struct Teacher{
	char name[32];
	int age;
}Teacher;

/* 定义结构体数组,同时初始化 */
Teacher t1[2] = {
	{"lily", 18},
	{"lilei", 22}
};

Teacher t1[2] = {"lily", 18, "lilei", 22};

2 结构体套指针

/* 结构体类型 */
typedef struct Teacher{
	char *name;
	int age;
}Teacher;

/* 结构体类型 */
typedef struct Teacher{
	char *name;
	char **stu;
	int age;
}Teacher;

3 结构体赋值

Teacher t1 = {"lily", "teacher", 18, "beijing"};
/**
* 相同类型的结构体变量,可以互相赋值
* 把t1每个成员的内容逐一拷贝到t2对应的成员中
*/
Teacher t2 = t1;

4 浅拷贝和深拷贝

  出现深拷贝和浅拷贝问题是因为,结构体中嵌套指针,而且动态分配空间,同类型结构体变量相互赋值,不同结构体成员指针变量指向了同一块内存

typedef struct Teacher{
	char *name;
	int age;
}Teacher;

Teacher t1;
t1.name = (char *)malloc(30);
strcpy(t1.name, "lily");
t1.age = 22;

Teacher t2;
t2 = t1;
/* 深拷贝,人为增加内存,重新拷贝一下 */
t2.name = (char *)malloc(30);
strcpy(t2.name, t1.name);

5 结构体偏移量(了解)

/* 结构体类型定义下来,内部的成员变量的内存布局已经确定 */
typedef struct Teacher{
	char name[64];//64
	int age; //4
	int id; //4
}Teacher;

Teacher t1;
Teacher *p = &t1;

int n1 = (int)(&p->age) - (int)p; /* 相对于结构体首地址 */
int n2 = (int)&((Teacher *)0)->age; /* 绝对0地址的偏移量 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值