天天看点

C基础-结构体-3-结构体与指针结合

为何要使用指向结构的指针?
第一,就像指向数组的指针比数组本身更容易操控(如,排序问题)一样,指向结构的指针通常比结构本身更容易操控。
第二,在一些早期的C实现中,结构不能作为参数传递给函数,但是可以传递指向结构的指针。
第三,即使能传递一个结构,传递指针通常更有效率。
第四,一些用于表示数据的结构中包含指向其他结构的指针

结构体与指针结合:
	1.成员指针:
		变量指针,
		函数指针
	2.指向结构体的指针
		在结构体内
		本身中
		其他结构体
		结构体外
		
		
//如何通过指针访问结构体成员变量
	struct stu *pa = &a;
	puts(a.name); //a.name 直接访问
	puts(pa->name);//pa->name 通过指针间接访问
	
	
	
	
//==============================
//结构体成员为指针
//==============================

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef  void(*FUN)(char *s);

struct stu
{
	int num;
	char name[20];
	int score;
	void (*study)(char *s);  
	void *private_data;  	 //私有数据
};

//方法
static void study(char *s)
{
	printf("the %s is in the study......\n",s);
}

static void mysleep(char *s){
	printf("the %s is sleeping \n",s);
}

void fun(void)
{
	struct stu a = 
	{
		.num = 1,
		.name = "xiaochao",
		.score = 100,
		.study = study,
	};
	
	int math_score = 120;
	
	a.private_data = (void *)&math_score;
	
	printf("the %s math_score is %d\n",a.name, *((int *)(a.private_data)) );
	
	a.study(a.name);
	
	a.study = mysleep; //mysleep,&mysleep 都可以
	(*a.study)(a.name);  
	
	a.private_data = (void *)mysleep; //函数名字是函数的地址
	
	((FUN)a.private_data)(a.name);
}

void main(void)
{
	fun();
}
	
	
//==============================
//指向结构体的指针
//==============================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef  void(*FUN)(char *s);

struct done
{
	void (*study)(char *s);
};

struct stu
{
	int num;
	char name[20];
	int score;	 
    struct done *mydo;	
	struct stu *next;        //指向本身数据类型的指针
	void *private_data;  	 //私有数据
};

//方法
static void mystudy(char *s)
{
	printf("the %s is in the study......\n",s);
}

static void mysleep(char *s){
	printf("the %s is sleeping \n",s);
}

void fun(void)
{
	struct stu a = 
	{
		.num = 1,
		.name = "xiaochao",
		.score = 100,
	};
	
	struct stu b = 
	{
		.num = 1,
		.name = "xiaosang",
		.score = 100,
	};
	
	a.next = &b;
	
	puts(a.next->name);
}

void fun1(void)
{
	struct stu a = 
	{
		.num = 1,
		.name = "xiaochao",
		.score = 100,
	};
	
	
	
	struct stu *pa = &a;
	puts(pa->name);
	
	
	//定义结构体变量mydone,*mydo指向mydone。
	struct done mydone =
	{
		.study=mystudy,
	};
	
	
	//赋值mydo
	a.mydo = &mydone;
	
	//直接访问,调用函数
	(*(a.mydo->study))(pa->name);
	
	//间接访问,另一种表示方法:调用函数
	 pa->mydo = &mydone;
	(pa->mydo->study)(pa->name);
	
	
}

void main(void)
{
	fun();
	fun1();
}


执行结果:
xiaosang
xiaochao
the xiaochao is in the study......
the xiaochao is in the study......