Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocate memory for struct

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 briefly touched on the new operator before going on to classes. Now I have to

"Dynamically allocate a student and then prompts the user for student’s first name, a last name, and A - number(ID number). "

my struct is written like

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

I tried Student student1 = new Student; but that doesn't work and I'm unsure as how I do this dynamically with a struct.

like image 879
sircrisp Avatar asked Feb 22 '12 15:02

sircrisp


Video Answer


2 Answers

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.

like image 148
parapura rajkumar Avatar answered Oct 19 '22 06:10

parapura rajkumar


This should be what you need:

std::unique_ptr<Student> x(new Student);
like image 8
Puppy Avatar answered Oct 19 '22 06:10

Puppy