2021-03-08

C++程序中地址(指针)作为型参、地址(引用)作为形参。可以改变实参,也更省内存。

//用地址作为形参 可以省略内存地址,因为:应为形参占用地址只有四个字节。而如果传递实参,有可能是结构体、有可能数组,这样使内存占用空间变大。
下面展示一些 内联代码片

// 
struct student
{
	string name;
	int	score;
};
struct teacher
{
	string name;
	struct student stu[5];
};

void creat_th_stu_name( teacher *th, int length1)
{
	string thname = "教师";
	string stuname = "学生";
	string nameSeed = "ABCDE";
	srand((unsigned int)time(NULL));
	//int length = sizeof(th[3]) / sizeof(teacher);
	for (int i = 0; i < length1; i++)
	{
		th[i].name = thname + nameSeed[i];
		//struct  student stu[5];
		for (int j = 0; j < 5; j++)
		{
			th[i].stu[j].name = stuname + nameSeed[j];
			th[i].stu[j].score = rand() % 60 + 41;
		}
	}
}
void print_th_stu_all(teacher th[], int length1)
{
	for (int i = 0; i < length1; i++)
	{
		cout << "\t姓名:" << th[i].name << endl;
		for (int j = 0; j < 5; j++)
		{
			cout << "\t姓名:" << th[i].stu[j].name << "\t分数:" << th[i].stu[j].score << endl;
		}
	}
}
int main()
{

	struct teacher th[3];

	int lent = sizeof(th) / sizeof(teacher);

	creat_th_stu_name(&th[0], lent);//这里th[0],是结构体首地址,如果变成th[1]那么他就会向后取地址,到th[4],这个4呢他没有定义,非法取变量值了。
	print_th_stu_all(th, lent);

	system("pause");

}
//数组作为形参 自动退化为地址传递
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值