I'm trying to create a linked list inside a function by passing a pointer to the head of the list. Inside the function, everything works perfectly. But when I get back to main()
, all of a sudden the pointer is NULL. So if I call the function again, it acts like I'm adding a node for the first time again.
What is the problem with my code?
struct course
{
int c_ID;
char *c_name;
struct course *c_next;
};
void new_course(struct course *c_head, struct course *c_tail); // adds a node
int main ( )
{
// variable declarations
int choice;
char y_n;
// create linked lists
struct course *c_head = NULL;
struct course *c_tail = NULL;
// print out menu, obtain choice, call appropriate function; loop if desired
do
{
printf("\t\t\t***MENU***\n"
" 1. Add a new course\n\n"
................................
"Enter the number of the menu option you wish to choose: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
new_course(c_head, c_tail);
if (c_tail == NULL)
{
printf("We're screwed.\n"); // this excecutes every time
}
break;
.....................
}
printf("Would you like to return to the main menu? Enter y for yes, n for no: ");
scanf(" %c", &y_n);
} while (y_n != 'n' && y_n != 'N');
// free courses
struct course *c_temp = NULL;
c_temp = c_head;
while (c_temp != NULL)
{
c_head = c_head->c_next;
c_temp->c_ID = 0; // reinitialize the student ID
c_temp->c_name[0] = '\0'; // reinitialize the student name string
free(c_temp->c_name); // return the string memory to the system
free(c_temp); // return the node memory to the system
c_temp = c_head; // set temp to next item in the list
}
return 0;
}
void new_course(struct course *c_head, struct course *c_tail)
{
// declare variables
int ID;
char name[50];
// obtain user input
printf("Enter the course ID number and the course name, separated by a space: ");
scanf("%d%s", &ID, name);
if(c_head == NULL) // no courses yet
{
c_head = (struct course *) malloc(sizeof(struct course)); // allocate memory for c_head
c_head->c_next = NULL;
c_tail = c_head; // update c_tail
}
else // the list already has nodes
{
c_tail->c_next = (struct course *) malloc(sizeof(struct course)); // allocate memory for new node
c_tail = c_tail->c_next; // update c_tail
c_tail->c_next = NULL;
}
c_tail->c_ID = ID; // assign ID to c_ID component of new node
c_tail->c_name = (char *) malloc(sizeof(char) * strlen(name) + 1); // allocate memory for c_name component of new node
strcpy(c_tail->c_name, name); // assign name to c_name component of new node
printf("%d = %d, %s = %s\n", c_head->c_ID, ID, c_tail->c_name, name); // this always works, proving the list was created and the assignments worked
return;
}