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");
}
//数组作为形参 自动退化为地址传递