结构体数组怎么初始化

2025-02-26 18:15:05
推荐回答(3个)
回答1:

// 有两种方法可以初始化结构体数组,如下例所示:
#include
#include
#include
#include
using namespace std;
// custom_type
typedef struct tagStudent
{
int Id;
string Name;
}Student;
int main()
{
// 设置左对齐
cout.flags(ios::left);
// 方式1: 适用于提前知道具体数据的情况
Student arrStu1[5] = {{1, "Name_1"}, {2, "Name_2"}, {3, "Name_3"}, {4, "Name_4"}, {5, "Name_5"}};
cout<<"Method_1:"< for (int i=0; i<5; i++)
{
cout< < }
cout< // 方式2: 具体数据可能稍后才能得到的情况
Student arrStu2[5];
memset(arrStu2, 0, sizeof(arrStu2));
cout<<"Method_2:"< for (int i=0; i<5; i++)
{
cout< < }
cout<}
// 测试结果:

回答2:

标准的答案!1.可以用memset初始化;
2.用循环初始化每个数组中的每个结构体元素。

回答3:

如下
C/C++ code
struct point{
point()
{
x=y=0.0f;
}
float x;
float y;
};