-
Problem in link list
Hi,
I have create a simple program for displaying a link list,but it is not working properly.
The code is as follow:
Code:
#include<stdio.h>
#include<stdlib.h>
struct linklist
{
int data;
struct linklist *next;
};
struct linklist *ptr;
void insert(linklist *ptr)
{
printf("INSIDE INSERT%u",ptr );
int num;
struct linklist *temp = ptr;
struct linklist *node = (struct linklist *)malloc(sizeof(struct linklist));
printf("\n Enter the data \n");
scanf("%d",&num);
node->data = num;
if ( ptr == NULL ) {
printf("INSIDE IF%u",ptr );
ptr = node;
node->next = NULL;
}
else {
printf("INSIDE ELSE");
while ( temp->next != NULL ) {
temp = temp->next;
}
temp->next = node;
node->next = NULL;
}
}
void display(linklist *ptr)
{
struct linklist *temp = ptr;
while ( temp != NULL ) {
printf("%d",temp->data );
temp = temp->next;
}
}
int main()
{
ptr = NULL;
int ch;
while ( 1 ) {
switch ( ch ) {
case 1:
insert(ptr);
break;
case 2:
display(ptr);
break;
case 3:
exit(0);
}
printf("\nEnter your choice ");
scanf("%d",&ch);
}
}
The problem is that in insert(ptr) function it always showing the ptr value 0 i.e NULL which I don't understand since the ptr I have declared as global so it should not be initialized to 0 every time the loop runs.
Can anybody explain me the behavior and solution to it.
Thanks
-
ptr should be allocated first...
-
Pointers themselves are passed by value. your global ptr is not modified by passing it to insert. To do that you'd need to either return ptr as well or prototype the function to take a pointer to a pointer, and pass it that.