Reputation: 9
I am doing a project for a programming subject. They ask to save a project in a linked list. Here you have my Struct:
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;
This is the 2nd phase of the project, the first one was using a simple array of structs, but this phase they want the same but with a linked list.
I have a function that I use to insert data in a struct. The function ask for an input and I save the data in the struct.
The insertion function:
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;
}
To save a string for title in the first phase I was using this:
getline(cin, no.title);
I want to do the same for the second phase and I did:
getline(cin, no->title);
But it gives this error:
Unhandled exception at 0x00E14E96 in Aplicacao.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
I don´t know what to do. Can you help me please?
Thanks a million.
Upvotes: 0
Views: 138
Reputation: 3861
As others have pointed out, you cannot use malloc to create an instance of the "No" struct because malloc will not call the constructor of the string. So the function becomes:
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;
}
Be aware that you should not free() on the object either. Instead, use the delete keyword.
Upvotes: 1