Dynamically allocate memory for struct

前端 未结 8 673
自闭症患者
自闭症患者 2020-12-31 12:21

I am taking a C++ class and have a assignment which requires me to dynamically allocate memory for a struct. I don\'t recall ever going over this in class and we only brief

8条回答
  •  没有蜡笔的小新
    2020-12-31 12:46

    Change you definition to

    struct Student 
    {
        string firstName, lastName, aNumber;
        double GPA;
    };
    

    Notice I have changed the placement of the struct keyword

    and you have to do Student* student1 = new Student instead.

    When you dynamically allocated memory for a struct you get a pointer to a struct.

    Once you are done with the Student you also have to remember to to release the dynamically allocated memory by doing a delete student1. You can use a std::shared_ptr to manage dynamically allocated memory automatically.

提交回复
热议问题