You have a struct node that has a member called name, which is of type string. When you do the malloc on line 23 (via evil macro locate), what you end up with is a block of raw, un-initialised memory.
struct node has no constructor to initialise its members, so you don't actually have a proper string object in your variable called name. You've got a bunch of random memory, and told the compiler it's a string. When the compiler tries to treat it as a string, probably by calling operator=() in line 24, all hell breaks loose.
If you had used operator new instead of malloc, the string constructor would have been called, a proper string object created, and the program would have gotten further, i.e. not crash, but it still wouldn't do what you want, because of a problem in insertNodeAtEnd().
You've really got a mixture of styles going on here, from the dodgy include statements, to the completely superfluous macros and the admixture of io solutions, just saying.
I know this isn't what you asked for, but I've made the code a little bit more C++ friendly. The only logic change I made was the while block at line 30, have a look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <string>
using namespace std;
struct node
{
string name;
struct node* next;
};
void createList(struct node**);
void writeCircularList(struct node*);
void insertNodeAtEnd(node** head, string name_n);
int main()
{
node* head = 0;
createList(&head);
writeCircularList(head);
}
void createList(node** head)
{
string name;
cout << "Write the first soldier's name:" << endl;
cin >> name;
while(name != "end")
{
insertNodeAtEnd(head, name);
cout << "Write another soldier's name:" << endl;
cin >> name;
}
}
void writeCircularList(node* head)
{
node* q = head;
do
{
cout << q->name << endl;
q = q->next;
}
while(q != head);
}
void insertNodeAtEnd(node** head, string name_n)
{
node *q = *head;
node *new_n = new node;
new_n->name = name_n;
if(*head == 0)
{
new_n->next = new_n;
*head = new_n;
}
else
{
while(q->next != *head)
{
q = q->next;
}
q->next = new_n;
new_n->next = *head;
}
}
|