Reputation: 27
I'm trying to define a struct with other structs as members of that struct but I'm not sure how this is done. The code I have looks like this so far:
typedef struct name
{
char fname[15];
char lname[15];
} Name;
typedef struct info
{
int grade;
char phone[13];
} Info;
typedef struct mark
{
int math;
int sci;
int eng;
} Mark;
typedef struct student
{
Name n;
Info i;
Mark m;
} Student;
int main()
{
Student class_list[30] = { };
}
Upvotes: 0
Views: 65
Reputation: 75688
If your question is how to initialize the array then the answer is like this:
Student class_list[2] = {
{{"John", "Doe"}, {8, "000-555-000"}, {1, 2, 3}},
{{"Jane", "Doe"}, {10, "000-555-001"}, {10, 8, 10}},
};
The reasons it works like this is because your classes are aggregates so you can use aggregate initialization.
Well, I initialized an array of 2 elements. You can see the syntax.
Some points for your program. The way of typedef struct
is a C idiom. In C++ you don't need it so please change all the definitions to:
struct Name
{
char fname[15];
char lname[15];
};
Also you should use std::array
instead of C arrays:
std::array<Student, 3> class_list {{
{{"John", "Doe"}, {8, "000-555-000"}, {1, 2, 3}},
{{"Jane", "Doe"}, {10, "000-555-001"}, {10, 8, 10}},
}};
Upvotes: 2