结构体所占的字节数:大于或者等于所有成员所占的字节的总和,并且是占字节最大成员所占字节数的整数倍
结构体只能声明变量,不能声明函数,可以用函数指针
函数指针定义:返回值(*函数指针名)(形参)
#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;
}