linked list basic

#include<iostream>
using namespace std;
int main()
{
struct node{
int x;
node *nxt;
};
node *node1,*node2;
cout<<sizeof(node1)<<"\n";
cout<<"Please enter number into the linked list\n";
node1->nxt=NULL;
cin>>node1->x;
cin>>node2->x;
return 0;}

please explain what is wrong with this code and a little about segmentation fault??

cause this is what a linked list is supposed to do;;
the first elements points to the second one
and the last element points to NULL
closed account (D80DSL3A)
You don't have any nodes to store data in yet, only pointers to nodes. These pointers are uninitialized so you are writing to "random" memory spaces (and this will cause a seg. fault).
You must allocate nodes for the pointers to point to.

As a bare start, you could make a 2 node list like so:
1
2
3
4
5
6
7
8
node * pNode = new node;// I prefer to use a p in a name for a pointer, so I know it's not a node
pNode->nxt = new node;// here 2 nodes are allocated to the pointers
pNode->nxt->nxt = NULL;// end of list
cin>>pNode->x;// this should work now
cin>>pNode->nxt->x;
cout << "values are" << pNode->x << " and " << pNode->nxt->x;// test this
delete pNode->nxt;// don't forget to release memory when done
delete pNode;
Thank you!!!
Topic archived. No new replies allowed.