结构体基本操作

目录

1 定义

2 初始化

3 引用 点操作符是干什么的

4 传参

5 结构体做函数参数


 

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值