Ngu*_*Tân 4 c++ string malloc segmentation-fault
我时出现分段错误(核心已转储)getline(cin, node->name)。
我通过str在输入函数中声明一个字符串来修复,然后node->name = str。但是跑到线上cin >> node->year仍然击中了细分故障。
struct client
{
int code;
string name;
int year;
float maths, physics, chemistry;
struct client *next;
};
struct client* input()
{
struct client *node = (struct client *)malloc(sizeof(struct client));
cout << "Code: ";
cin >> node->code;
cout << "Name: ";
cin.ignore();
getline(cin, node->name);
cout << "Year: ";
cin >> node->year;
cout << "Maths, Physics, Chemistry: ";
cin >> node->maths >> node->physics >> node->chemistry;
node->next = NULL;
return node;
}
Run Code Online (Sandbox Code Playgroud)
由于malloc用于分配内存,因此不会node初始化任何内容。特别是string name不会正确初始化,并且在尝试使用它时会引起问题,因为涉及它的任何功能都依赖于正确构造字符串的事实。代替这个:
struct client *node = (struct client *)malloc(sizeof(struct client));
Run Code Online (Sandbox Code Playgroud)
做这个:
client *node = new client;
Run Code Online (Sandbox Code Playgroud)
这样,即可正确初始化其中的node(和name)。
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |