I have a linked list which stores student's information. The list includes one char * and two int, my problem arises when I try to initialize my char * with a string, as I get Seg Fault when I do so.
Things I've tried: using strcpy instead of = as well as dynamically allocating memory.
typedef struct Student{
int age,id;
char *name;
struct Student *next;
}Student;
struct Student *head = NULL;
Create linked list function
Student *create (){
char name[128];
Student *newStudent = (Student*)malloc(sizeof(Student));
newStudent->name = malloc(sizeof(Student) + 1);
newStudent->age = (rand() % (35 - 18 + 1)) + 18; // age range of student from 18-35
newStudent->id = rand() % 1000000 + 100000; // 6 digit id
scanf("%127s", name);
strcpy(newStudent->name, name);
newStudent->next = NULL;
return newStudent;
}
insert function
Student *insert(Student *newStudent){
Student *ptr = head;
if (head == NULL)
return newStudent;
while (ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = newStudent;
return head;
}
Build function
Student *build(){
int size;
Student *newStudent = (Student*)malloc(sizeof(Student));
printf("Enter size of linked list: ");
scanf("%d",&size);
for (int i=0; i<size; i++){
newStudent = create();
head = insert(newStudent);
}
return head;
}
print and main function
void print(Student *head){
for (Student *ptr = head; ptr != NULL; ptr = ptr->next)
printf("Student info\nName: %s, ID: %d, age: %d\n", ptr->name, ptr->id, ptr->age);
printf("\n");
}
int main(){
srand(time(0));
head = build();
print(head);
return 0;
}
unionfor the name and age/id fields in this case.unionwill not store all three members separately. Instead it will store members one at a time in one location. So when you setu.ageyou will eraseu.nameor vice-versa.