linked list: struct pointers as parameters

Hello people,
I am making a program to add nodes to create a linked list, and to display it. At first when I ran the code in the main itself, there were no problems.

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
struct node
{
	int info;
	node *next;
};

int main()
{
	node *ptr, *top=NULL, *bot=NULL;

	char ch='y';
	while(ch=='y')
	{
		ptr=new node;
		cout<<"Enter info: ";
		cin>>ptr->info;

		if(top==NULL)
		{
			top=ptr;
			bot=ptr;
		}

		else
		{
			ptr->next=top;
			top=ptr;
		}

		cout<<"\nAdd new node?: ";
		cin>>ch;
	}
	
        //DISPLAY
	for(node *po=top;po!=bot;po=po->next)
	cout<<po->info<<" ";
	cout<<top->info;

	getch();
	return 0;
}


This worked fine and displayed it too. But when I decided to make it a function and pass the pointers as parameters, it ran the function part, but when it came back to main, it did not do the display part.

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
void createlist(node *ptr, node *top, node *bot)
{
    char ch='y';
	while(ch=='y')
	{
		ptr=new node;
		cout<<"Enter info: ";
		cin>>ptr->info;

		if(top==NULL)
		{
			top=ptr;
			bot=ptr;
		}

		else
		{
			ptr->next=top;
			top=ptr;
		}

		cout<<"\nAdd new node?: ";
		cin>>ch;
	}
}

int main()
{
	node *ptr, *top=NULL, *bot=NULL;
	createlist(ptr, top, bot);

        //THIS IS DISPLAYED ON THE SCREEN
	cout<<"\nBack in main()";

        //THIS IS NOT
	for(node *po=top;po!=bot;po=po->next)
	cout<<po->info<<" ";
	cout<<top->info;

	getch();
	return 0;
}


It says "windows is searching for a solution" and then says "A problem caused the program to stop working correctly".

What could be wrong? Thanks in advance.
Last edited on
createlist takes it's parameters by value. Any changes made to them are not reflected on the variables in the calling code, so on line 37 you dereference a null pointer.

You could pass the pointers by reference: void createlist(node*& ptr, node*& top, node*& bot)

I really thought that passing pointers necessarily meant that they were passed by reference. But now I realise it is not so. It does work. Thank you.
I really thought that passing pointers necessarily meant that they were passed by reference


In general, that is correct. However, that is only true for the data pointed to by the pointers: The pointers themselves are copied. That is why if you want to modify the actual pointers, they need to be passed by reference.
Topic archived. No new replies allowed.