C++ 传递数组给函数:
①C++ 传数组给一个函数,数组类型自动转换为指针类型,因而传的实际是地址。也就是说遍历函数中数组参数,实际上是遍历实参,而且也会改变外部实参
②数组名就是数组首地址,如int array[5]
,那么array
就是首地址,但是array[i]
就是第 i
个值,这个有点类似指针引用。
# include<iostream>
# include<string>
using namespace std;
struct Hero
{
// 姓名
string name;
//年龄
int age;
//性别
string sex;
};
void bubblesort(struct Hero heroarray[], int len)
{
// int len = sizeof(heroarray) / sizeof(heroarray[0]);
for (int i = 0; i < len -1; i++)
{
for (int j = 0; j < len -i -1; j++)
{
if (heroarray[j].age > heroarray[j + 1].age)
{
struct Hero temp = heroarray[j];
heroarray[j] = heroarray[j + 1];
heroarray[j + 1] = temp;
}
}
}
}
void printinfo(struct Hero heroarray[], int len)
{
// len = sizeof(heroarray) / sizeof(heroarray[0]);
cout << len << endl;
for (int i = 0; i < len; i++)
{
cout << "人名: " << heroarray[i].name << " 年龄:" << heroarray[i].age << endl;
};
}
int main()
{
//1、设计英雄的结构体
//2、对数组进行排序,按照年龄进行升序排列
struct Hero heroarray[5] = {
{"刘备", 23, "男"},
{"关羽", 22, "男"},
{"貂蝉", 18, "女"},
{"赵云", 22, "男"},
{"西施", 33, "女"}
};
cout << sizeof(heroarray) << endl;
int len = sizeof(heroarray) / sizeof(heroarray[0]);
printinfo(heroarray, len);
bubblesort(heroarray, len);
printinfo(heroarray, len);
return 0;
}
out:
360
5
人名: 刘备 年龄:23
人名: 关羽 年龄:22
人名: 貂蝉 年龄:18
人名: 赵云 年龄:22
人名: 西施 年龄:33
5
人名: 貂蝉 年龄:18
人名: 关羽 年龄:22
人名: 赵云 年龄:22
人名: 刘备 年龄:23
人名: 西施 年龄:33
但是以下:
# include<iostream>
# include<string>
using namespace std;
struct Hero
{
// 姓名
string name;
//年龄
int age;
//性别
string sex;
};
void bubblesort(struct Hero heroarray[])
{
int len = sizeof(heroarray) / sizeof(heroarray[0]);
for (int i = 0; i < len -1; i++)
{
for (int j = 0; j < len -i -1; j++)
{
if (heroarray[j].age > heroarray[j + 1].age)
{
struct Hero temp = heroarray[j];
heroarray[j] = heroarray[j + 1];
heroarray[j + 1] = temp;
}
}
}
}
void printinfo(struct Hero heroarray[])
{
len = sizeof(heroarray) / sizeof(heroarray[0]);
cout << len << endl;
for (int i = 0; i < len; i++)
{
cout << "人名: " << heroarray[i].name << " 年龄:" << heroarray[i].age << endl;
};
}
int main()
{
//1、设计英雄的结构体
//2、对数组进行排序,按照年龄进行升序排列
struct Hero heroarray[5] = {
{"刘备", 23, "男"},
{"关羽", 22, "男"},
{"貂蝉", 18, "女"},
{"赵云", 22, "男"},
{"西施", 33, "女"}
};
cout << sizeof(heroarray) << endl;
int len = sizeof(heroarray) / sizeof(heroarray[0]);
printinfo(heroarray);
bubblesort(heroarray);
printinfo(heroarray);
return 0;
}
out:
0
0
以上出现不同结果,是因为 函数 printinfo
和bubblesort
的参数 heroarray
的首地址指向一样,后续遍历实际是按照 实参在遍历