目录
1 定义
2 初始化
3 引用 点操作符是干什么的
=的时候才操作内存
4 传参
为何会失败呀?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//1
struct teacher
{
int id;
char name[64];
};
struct teacher t5 = { 5, "laoshi5" };
//2
struct {
int id;
char name[64];
} t3, t4;//匿名的结构体类型 类型只能定义一次, 不能通过函数传参
//3
typedef struct _teacher
{
int id;
char name[64];
} teacher_t; //最常用的写法
/*
struct _teacher
{
int id;
char name[64];
};
typedef struct _teacher teacher_t;
*/
void print_teacher(struct teacher* p1)
{
printf("id = %d\n", p1->id);
printf("name = %s\n", p1->name);
}
void print_teacher2(struct teacher t) //t = t1 int a = b; struct teacher t1 = t2
{
printf("===== print_teacher2===\n");
printf("id = %d\n", t.id);
printf("name = %d\n", t.name);
}
void copy(struct teacher to, struct teacher from)
{
to = from;
}
void copy2(struct teacher *to, struct teacher *from)
{
*to = *from;
}
/*
void print_teacher2(struct {
int id;
char name[64];
})
*/
int main(void)
{
struct teacher t1;
struct teacher t8;
teacher_t t6 = {6, "laoshi6"};
//teacher t7; // C语言中 定义一个结构体 必须加上struct 关键字 C++不用加
t1.id = 10;
strcpy(t1.name, "laoshi1");
print_teacher(&t1);
print_teacher(&t5);
print_teacher2(t1); //
printf("=====\n");
copy2(&t8, &t1);
print_teacher(&t8);
struct teacher t9 = t1; //int a = b;
return 0;
}
5 结构体做函数参数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct teacher
{
int id;
char name[64];
};
//开辟 struct teacher 的空间
void create_teachers(struct teacher **tpp, int num)
{
struct teacher *p = NULL;
if (tpp == NULL) {
return;
}
p = (struct teacher *)malloc(sizeof(struct teacher) *num);
if (p == NULL) {
return;
}
*tpp = p;
return;
}
void print_teachers(struct teacher *tp, int num)
{
int i = 0;
printf("=======\n");
for (i = 0; i < num; i++) {
printf("id :%d\n", tp[i].id);
printf("name : %s\n", tp[i].name);
}
}
void free_teachers(struct teacher **tpp)
{
if (tpp == NULL) {
return;
}
struct teacher *tp = *tpp;
if (tp != NULL) {
free(tp);
*tpp = NULL;
}
return;
}
int main(void)
{
struct teacher * tp = NULL;
int i = 0;
int num = 3;
create_teachers(&tp, num);
for (i = 0; i < num; i++) {
printf("enter %d 's id: ", i + 1);
scanf("%d", &tp[i].id);
printf("enter %d's name:", i + 1);
scanf("%s", tp[i].name);
}
print_teachers(tp, num);
free_teachers(&tp);
if (tp == NULL) {
printf("freed succ!\n");
}
return 0;
}