I am trying to create a simple C program while learning about the concepts about pointers, linked list and header files.
I want to create a simple C program by clubbing all these concepts together for better understanding.
My code and its explanation is as follows:
I have a header file "header1.h " where I have declared the structure which is to be shared between various source files and also the "head" variable of the linked list.
The header file is as follows:
header1.h
struct node{
char * name;
struct node* next;
};
extern struct node* head;
Now, I have the main source-file named "start_prog.c" which has got the "main" function
and the menu which will control the execution of the of the program.
Menu has various options such as Add element ,Delete element , Reverse List etc (for simplicity I will only present two options here viz, Insert and Print list which are most important).
from the start_prog.c I call the "create" function which will add the element to the list.
If the list does not exist then it will create one else It will append the element to the list after the last element.
The create function is defined in another source file "create.c".
Both the files are as follows:
start_prog.c:
#include<stdio.h>
#include<stdlib.h>
#include "header1.h" //include the header file
struct node* head = NULL; //Define the external variable head to be null initially
struct node* create();
void main(void){
int option;
do{
printf("\nplease select the option : \n\t\t1)add element \n\t\t2)Print List\n");
scanf("\n%d",&option);
switch(option){
case 1:
head = create();
break;
case 2:
print_list();
break;
}
}while(option != 3);
}
and the create.c file is as follows:
#include<stdio.h>
#include<stdlib.h>
#include "header1.h"
//this function creates the linked list if the list is null or inserts the
//element at the end of the list.
struct node* create() {
if(head == NULL){
//create a new list and return head.
printf("\nhead is null\n");
struct node* newnode = (struct node*)malloc(sizeof(struct node));
char * new_name;
printf("\nplease enter the new name\n ");
scanf("%s\n", new_name);
newnode -> name = new_name;
newnode -> next = NULL;
head = newnode;
return head;
}
else if(head != NULL){
printf("\nhead is not null\n ");
struct node* newnode = (struct node*)malloc(sizeof(struct node));
char * new_name;
printf("\n Please Enter the new name \n");
scanf("%s\n", new_name);
newnode -> name = new_name;
newnode -> next = NULL;
struct node* ptr = NULL;
ptr = head;
while((ptr -> next) != NULL){
ptr = ptr -> next;
}
ptr -> next = newnode;
return head;
}
}
when I run all these programs together I get Garbage values in the head and Segmentation fault error. What is Wrong in my code. What is the thing that I am missing. I feel that I am close to understand the concepts but missing some important point due to which I am not
able to write the program properly. Please find the bug/error in my code and the fault in my understanding.
Thankyou!