c++11 - C++ linked list crashed -
i new on data structure. trying write linked list string , display list screen. crash @ node *p = create("i "); warning of access violation writing location. here code, don't know how fix it. please help. thank much.
#include <iostream> #include <cstdlib> #include <string> using namespace std; struct node { string data; node *prev, *next; }; node* create (string value) { node *temp = (node*)malloc(sizeof(node)); if (null==temp) return null; temp->data=value; temp->next=null; temp->prev=null; return temp; } void addhead (node* head, string value) { node *temp = new node; temp->data=value; temp->next=head; head->prev=temp; head = temp; temp->prev = null; } void addtail (node* head, string value) { node* s = new node; node* temp = new node; s=head; while (s->next!=null) s = s->next; s->next = temp; temp->prev = s; } void display (node* head) { if (head==null) return; else { cout << head->data << " "; display (head->next); } } int main() { node *p = create("i "); addtail(p, "want "); addtail(p, "cookies "); display(p); return 0; }
you need create node
using new
, not malloc
, in create
function. using malloc, constructor node
not called, , assignment data
access uninitialized string object.
Comments
Post a Comment