关于C语言结构体数组如何作为参数传入函数

1.不多说上代码

#include
typedef enum
{
	female,male
}Sextype;
typedef struct
{
	Sextype sextype;
	int Number;
}School;
typedef struct
{
	int MaleSum;
	int FemaleSum;
	int AllSum;
}Num;
Num Sumscore(School* sn, int n);
int main()
{
	Sn shool[3] = { {female,10},{male,15},{female,20} };
	Num num;
	num = Sumscore(shool,3);
	printf("male=%d,female=%d,all=%d\n", num.MaleSum,num.FemaleSum,num.AllSum);
	return 0;
}
Num Sumscore(School* sn,int n)
{
	Num temp = {0,0,0};
	for (int i = 0; i < n; i++)
	{
		if (sn[i].sextype == female)
			temp.FemaleSum += sn[i].Number;
		else
			temp.MaleSum += sn[i].Number;
		temp.AllSum += sn[i].Number;
	}
	return temp;
}

如果初学者对typedef这个函数的使用不熟悉的话,下面这串代码去掉typedef

#include
enum Sextype
{
	female,male
};
struct School
{
	enum Sextype sextype;
	int Number;
};
struct Number
{
	int MaleSum;
	int FemaleSum;
	int AllSum;
};
struct Number Sumscore(struct School* sn, int n);
int main()
{
	struct School school[3] = { {female,10},{male,15},{female,20} };
	struct Number num;
	num = Sumscore(school,3);
	printf("male=%d,female=%d,all=%d\n", num.MaleSum,num.FemaleSum,num.AllSum);
	return 0;
}
struct Number Sumscore(struct School* school,int n)
{
	struct Number temp = {0,0,0};
	for (int i = 0; i < n; i++)
	{
		if (school[i].sextype == female)
			temp.FemaleSum += school[i].Number;
		else
			temp.MaleSum += school[i].Number;
		temp.AllSum += school[i].Number;
	}
	return temp;
}

结果运行效果截图:
关于C语言结构体数组如何作为参数传入函数_第1张图片
运行没问题,这里解释一下如何把结构体数组作为参数传入函数,其实在C语言中,任何数组都可以用首地址加上数组长度的方式传入函数,结构体数组也是数组,同样可以以首地址加上数组长度的方式传入函数,需要注意是仅仅只有别把传入的数据类型给搞错了。(我想学到结构体这个地方了,指针应该比较熟悉了吧,如果不理解为什么首地址加上长度可以表示数组的原因,可以搜索数组传入函数这个问题)

你可能感兴趣的:(关于C语言结构体数组如何作为参数传入函数)