gpt4 book ai didi

c++ - 带字符串的链表

转载 作者:行者123 更新时间:2023-11-28 06:15:36 27 4
gpt4 key购买 nike

我正在做一个编程主题的项目。他们要求将项目保存在链表中。这里有我的结构:

typedef struct dados {

int ID;

string title;

char institution[150];

char investigator[150];

string keywords[5];

float money;

struct dados *next; //pointer to next nodule

}No;

这是项目的第二阶段,第一个阶段是使用一个简单的结构数组,但是这个阶段他们想要相同的但有一个链表。

我有一个函数可以用来在结构中插入数据。该函数要求输入,我将数据保存在结构中。

插入函数:

No * insertBegin(No * head){

No * newNode;

newNode= (No *)malloc(sizeof(No));

cout << endl << "Qual e o titulo do projeto?" << endl << endl;

getline(cin, newNode->titulo)

//More data like this, on the end:

newNode->next= head;
}

为了在第一阶段为标题保存一个字符串,我使用了这个:

getline(cin, no.title);

我想为第二阶段做同样的事情,我做到了:

getline(cin, no->title);

但它给出了这个错误:

Unhandled exception at 0x00E14E96 in Aplicacao.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.

我不知道该怎么办。你能帮帮我吗?

感谢一百万。

最佳答案

正如其他人所指出的,您不能使用 malloc 创建“No”结构的实例,因为 malloc 不会调用字符串的构造函数。所以函数变为:

No * insertBegin(No * head){
No * newNode;

//newNode= (No *)malloc(sizeof(No));
newNode = new No();

cout << endl << "Qual e o titulo do projeto?" << endl << endl;

getline(cin, newNode->titulo)

//More data like this, on the end:

newNode->next= head;
}

请注意,您也不应该在对象上使用 free()。相反,使用 delete关键字。

关于c++ - 带字符串的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405907/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com