结构体
- 定义结构体的方式
struct Teacher {
char name[50];
int age;
};
struct Teacher t1;
struct Teacher t2 = {"zhangsan", 10};
void fun() {
//操作结构体的属性
printf("t2: %s, %d", t2.name, t2.age)
}
struct Teacher {
char name[50];
int age;
} t;
//定义结构体类型
typedef struct Teacher {
char name[50];
int age;
} Teacher;
struct Teacher t1;
Teacher t2;
//定义结构体指针变量
struct Teacher {
char name[50];
int age;
};
struct Teacher *p = NULL;
p = &t2; //第一个方法里的t2
printf("t2: %s, %d", t2.name, t2.age);
printf("t2: %s, %d", (*p).name, (*p).age);
printf("t2: %s, %d", p->name, p->age);
//定义结构体时不能给属性赋值
//结构体只是一个类型,还没有分配空间
//只有根据类型定义变量时,才会分配空间,有空间后才能赋值
struct Teacher {
char name[50];
//int age = 20; 编译无法通过
}
- 结构体赋值
相同类型的两个结构体变量,可以相互赋值
把t1成员变量的值拷贝到t2成员变量的内存
Teacher t1 = {"zhangsan", 12};
Teacher t2 = t1;
结构体数组赋值
Teacher t[3] = {"zhangsan", 1, "zhangsan", 2, "zhangsan", 3}
Teacher *p = (Teacher *)malloc(3 * sizeof(Teacher));
//if判空
char buf[50] = "123456789abc";
for(int i=0;i<3;i++) {
strcpy(p[i].name, buf);
p[i].age = 10+i;
}
- 结构体嵌套一级指针
Teacher结构体类型定义
typedef struct Teacher {
char *name;
int age;
}
Teacher t; //普通变量
t.name = (char *)malloc(30);
strcpy(t.name, "abcdef");
t.age = 19;
//判空
free(t.name);
Teacher *p; //指针变量
p = (Teacher *)malloc(sizeof(Teacher));
p->name = (char *)malloc(30));
strcpy(p->name, "abcdef");
p->age = 10;
//判空
free(p->name);
free(p);
Teacher *p; //数组变量
//Teacher p[3];
p = (Teacher *)malloc(sizeof(Teacher) * 3);
for(int i=0;i<3;i++) {
p[i].name = (char *)malloc(30);
//(*p)->name
strcpy(p[i].name, "abcdef");
p[i] = 10;
}
//各种判空
for(int i=0;i<3;i++) {
free(p[i].name);
}
free(p);
-
深浅拷贝
结构体中嵌套指针,且动态分配内存空间,并且同类型结构体间变量赋值,导致不同结构体成员指针变量指向同一块内存,为浅拷贝。
深拷贝需要手动malloc一块新的空间赋值。 -
结构体嵌套结构体
typedef struct A {
int a;
char *c;
} A;
typedef struct B {
int m;
//struct A a; /编译报错,无法确定大小
struct A *a; //指针大小位数固定
}
结构体不可以嵌套本结构体的普通变量,普通变量大小无法确定
(类型本质:固定大小的内存块别名)
结构体可以嵌套本结构体的指针变量,指针变量固定4字节(32位)
网友评论