How to initialize an array of struct in C++? How to initialize an array of struct in C++? arrays arrays

How to initialize an array of struct in C++?


The syntax in C++ is almost exactly the same (just leave out the named parameters):

mydata data[] = { { "Archimedes", 2.12 },                   { "Vitruvius", 4.49 } } ;

In C++03 this works whenever the array-type is an aggregate. In C++11 this works with any object that has an appropriate constructor.


In my experience, we must set the array size of data and it must be at least as big as the actual initializer list :

//          ↓mydata data[2] = { { "Archimedes", 2.12 },                   { "Vitruvius", 4.49 } } ;


The below program performs initialization of structure variable. It creates an array of structure pointer.

struct stud {    int id;    string name;    stud(int id,string name) {        this->id = id;        this->name = name;    }    void getDetails() {        cout << this->id<<endl;        cout << this->name << endl;    }}; int main() {    stud *s[2];    int id;    string name;    for (int i = 0; i < 2; i++) {        cout << "enter id" << endl;        cin >> id;        cout << "enter name" << endl;        cin >> name;        s[i] = new stud(id, name);        s[i]->getDetails();    }    cin.get();    return 0;}