segmentation fault is given whY?Code:struct node {int key;node * next}; node * head,*tmp; head=tmp; for(int i=0;i<nPoints;i++) { tmp=new node; tmp->key=i; tmp=tmp->next; tmp=NULL; } cout<<head->next->key;
This is a discussion on link list within the C++ Programming forums, part of the General Programming Boards category; segmentation fault is given whY? Code: struct node {int key;node * next}; node * head,*tmp; head=tmp; for(int i=0;i<nPoints;i++) { tmp=new ...
segmentation fault is given whY?Code:struct node {int key;node * next}; node * head,*tmp; head=tmp; for(int i=0;i<nPoints;i++) { tmp=new node; tmp->key=i; tmp=tmp->next; tmp=NULL; } cout<<head->next->key;
-mayfda-
I find it hard to understand what your trying to accomplish by the way you code. If you could give me more detailed information I could probably help better, but fromt he code you have given me.
tmp=tmp->next;
You have just set temp to equal a new node thefore next is going to equal 0. Don't you want to assign this temporary value to the next one on the head node.??
Last edited by bartybasher; 10-11-2003 at 10:07 AM.
I dont know if this helps you but I created a linked list program that does the same as I think you want to acheive.
Code:#include <iostream.h> class Node { public: Node(): itsNext(0), itsKey(0) {} ~Node() {} void Insert (Node * theNode); int getKey()const { return itsKey; } void setKey(int key) { itsKey = key; } void Show(); private: Node *itsNext; int itsKey; }; void Node::Insert(Node *theNode) { if (itsNext == 0) itsNext = theNode; else itsNext->Insert(theNode); } void Node::Show() { cout << itsKey; if (itsNext == 0) return; itsNext->Show(); } class LinkedList { public: LinkedList(): itsHead(0) {} void Insert(Node *theNode); void Show(); private: Node * itsHead; }; void LinkedList::Insert(Node *theNode) { if (itsHead == 0) itsHead = theNode; else itsHead->Insert(theNode); } void LinkedList::Show() { if (itsHead == 0) return; itsHead->Show(); } int main() { LinkedList theList; Node *theTemp; for (int i = 0; i < 10; i++) { theTemp = new Node; theTemp->setKey(i); theList.Insert(theTemp); } theList.Show(); return 0; }