creating an array of structs in c++
creating an array of structs in c++
Try this:
Customer customerRecords[2] = {{25, Bob Jones},
{26, Jim Smith}};
You cant use an initialization-list for a struct
after its been initialized. Youve already default-initialized the two Customer
structs when you declared the array customerRecords
. Therefore youre going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator=
member function to initialize the array members.
So either of the following could work:
Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = Bob Jones;
customerRecords[1].uid = 25;
customerRecords[1].namem = Jim Smith;
Or if you defined a constructor for your struct like:
Customer::Customer(int id, string input_name): uid(id), name(input_name) {}
You could then do:
Customer customerRecords[2];
customerRecords[0] = Customer(25, Bob Jones);
customerRecords[1] = Customer(26, Jim Smith);
Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because youre actually initializing the Customer
structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.
creating an array of structs in c++
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, Bob Jones};
customerRecords[1] = (Customer){26, Jim Smith};
But its rather unportable.