I am making a linked list program for my basic C assignment.
However, I will always get the force closed error on .exe and get a segmentation fault on Ubuntu.
I tried to break it down and rewrite but I have no idea where the code fails.
I’d appreciate your help.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char name[20];
int mark;
struct node *next;
};
struct node *addnode(char name[], float mark);
int main(void){
int j = 0;
char StdName[10];
float StdMarks;
struct node *head = NULL;
struct node *curr = NULL;
head = curr = addnode('\0',0.0);
for(j=0; j<3; j++){
printf("\nEnter StdName >>");
printf("\nMarks for %s >>", StdName);
curr -> next = addnode("", 5.5);
curr = curr->next;
}
curr = head -> next;
j = 0;
printf("\nnode\tName\tMarks");
while(curr){
printf("\n%d\t%s\t%5.2f", j++, curr->name, curr->mark);
curr=curr->next;
}
return 0;
}
struct node *addnode(char name[], float mark){
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
strcpy(temp->name,name);
temp->mark=mark;
temp->next=NULL;
return (temp);
}
A few mistakes:
'\0'is not achar[], but acharwhose value is0and converted to achar*(NULLpointer). Use""for an empty string. The compiler should have emitted a warning for this. Compile with warning level at highest and treat warnings as errors (so you cannot ignore them). Forgccthe flags are-Wall -Werror.StdNameis not initialised and is never populated but is used in aprintf("%s")call.