【发布时间】:2018-11-14 06:12:40
【问题描述】:
我正在尝试为结构动态分配内存,但在动态分配内存时出现错误
#include <string>
using namespace std;
#define MAX_GRADES 5
typedef struct _Student
{
string id;
string name;
double grades[MAX_GRADES];
double average;
}Student;
Student *update_list;
int main()
{
Student *n = (*Student) malloc(sizeof(n));
return 0;
}
main.cpp: In function ‘int main()’:
main.cpp:26:24: error: expected primary-expression before ‘)’ token
Student *n = (*Student) malloc(sizeof(Student));
^
【问题讨论】:
-
重要提示:
std::string是一个相当复杂的类。仅当其众多构造函数中的至少一个成功初始化该类时,它才有效。malloc是一个 C 函数。 C 不知道构造函数是什么,因此没有运行string构造函数。这会留下id和name定时炸弹等待炸毁你的程序。不要malloc一个 C++ 类,除非你知道该类是一个 POD type 或者在使用前将使用 placementnew。
标签: c++