I am trying to create a linked list and then echo the node values to the console. But using a function outside the main function and calling it is causing segmentation fault(core dumped). I can't figure it out why.
The following code works :
#include<iostream>
using std::cout;
using std::endl;
struct node
{
int val;
node* next;
};
void printList(node* start)
{
node* temp;
temp = start;
int i = 0;
while(temp->next != NULL)
{
cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
temp = temp->next;
i++;
}
}
int main()
{
node* start;
node* temp;
start = new node;
temp = start;
for(int i = 0; i < 10; i++)
{
temp->val = i*10;
temp->next = new node;
temp = temp->next;
}
temp->val = 0;
temp->next = NULL;
printList(start);
return 0;
}
But this throws a segmentation fault
#include<iostream>
using std::cout;
using std::endl;
struct node
{
int val;
node* next;
};
void createList(node* start)
{
node* temp;
start = new node;
temp = start;
for(int i = 0; i < 10; i++)
{
temp->val = i*10;
temp->next = new node;
temp = temp->next;
}
temp->val = 0;
temp->next = NULL;
}
void printList(node* start)
{
node* temp;
temp = start;
int i = 0;
while(temp->next != NULL)
{
cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
temp = temp->next;
i++;
}
}
int main()
{
node* start;
createList(start);
printList(start);
return 0;
}