为struct动态分配内存 [英] Dynamically allocate memory for struct
问题描述
我采取一个C ++类,并有一个赋值,需要我动态分配内存的结构。我不记得有没有在课堂上讨论这个问题,我们只是简单地触及 new
运算符。现在我必须
动态分配学生,然后提示用户输入学生的名字,姓氏和A-号码(ID号) p>
my struct的写法如下:
struct Student
{
string firstName,lastName,aNumber;
double GPA;
}
我试过 Student student1 = new Student;
但是这不工作,我不确定如何使用一个结构动态。
解决方案
struct Student Student
{
string firstName,lastName,aNumber;
double GPA;
}
注意我已经改变了struct关键字
而你必须 Student * student1 = new Student
。
当你为结构动态分配内存时,你得到一个结构的指针。
一旦你完成了学生记住要通过执行 delete student1
来释放动态分配的内存。您可以使用 std :: shared_ptr 自动管理动态分配的内存。
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.
解决方案 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.
这篇关于为struct动态分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!