c语言—指针基础(9:结构体和函数指针)

结构体所占的字节数:大于或者等于所有成员所占的字节的总和,并且是占字节最大成员所占字节数的整数倍
结构体只能声明变量,不能声明函数,可以用函数指针
函数指针定义:返回值(*函数指针名)(形参)
#include "stdafx.h"

struct Student
{
	short age;     //2个字节
	char gender;   //1个字节
	int score1;     //4个字节
	double score2;  //8个字节
	void(*study)();
	double(*totalScore) (int,double);  //定义函数指针
};

double calSumScore(int score1, double score2) {
	return score1 + score2;
}

void mustStudyHard() {
	printf("We must study hard!\n");
}

int main() {
	//struct关键字不能省去
	struct Student student = {18,'f',99,99.5};
	student.totalScore = &calSumScore;  //结构体中定义的函数指针指向具体的函数
	student.study = &mustStudyHard;
	student.study(); //调用
	printf("totalScore=%.2f\n", student.totalScore(student.score1, student.score2)); //调用
	printf("年龄:%hd,所占字节:%d\n",student.age,sizeof(student.age));
	printf("性别:%c,所占字节:%d\n",student.gender, sizeof(student.gender));
	printf("分数:%d,所占字节:%d\n",student.score1, sizeof(student.score1));
	printf("结构体占:%d个字节\n",sizeof(student));

	//结构体指针,指针指向student这个变量
	struct Student* stu = &student;
	stu->score1 = 80;
	stu->score2 = 86.4;
	printf("totalScore=%.2f\n", stu->totalScore(stu->score1, stu->score2));
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值