I write a link list program of three functions 1. "ref.h" 2. "main.c" 3. "create.c"
"create.c" accepts parameters from main.c and add an new item to the link list
I use pointer to pass the parameters to create.c, but I found my "front" variable in "create.c" is always NULL even though I have assigned new to it in the first item to be added.
Could anyone help me to find why? I have stuck in this question for hours =.=
Thank you very much!!
ps. I run my program in Linux environment
In ref.h
Code:
#include <stdio.h>
struct data{
int postcode;
struct data *next;
};
In main.c
Code:
#include "ref.h"
void main()
{
struct data *front=NULL;
struct data *end=NULL;
int a;
while(1)
{
printf("Add item to link list:\n");
printf("Enter 1 to add link list\n");
scanf("%d",&a);
switch(a)
{
case 1:{
create(front,end);
break;
}
default:
exit(0);
}
}
}
In create.c
Code:
#include "ref.h"
void create(struct data *front,struct data *end)
{
struct data *new=(struct data *)malloc(sizeof(struct data));
printf("Please enter the postcode:\n");
int i;
scanf("%d",&i);
new->postcode=i;
new->next=NULL;
if(front==NULL) each time the create function only runs in if
{
front=new;
end=new;
printf("First create!\n");
}
else
{
end->next=new;
end=new;
printf("In create!\n");
}
}