Greetings again,
I have this problem again on C but now using struct.
Having this structure of student
struct student {
char *name;
int age;
}
I wanted to a list where I could add a number of Student and can also view all of its elements. Here’s the code I have done so far.
#include<stdio.h>
#include<stdlib.h>
// struct student ...
void add(student **list, char* name, int age) {
student* temp = (student *)malloc(sizeof(student));
temp->name = name
temp->age = age;
*list = temp;
*(list++) = (student *)malloc(sizeof(student));
}
void view(student **list) {
student* data = *list;
while(data != '\0') { printf("%s%i", data->name, data->age); *(data++); }
}
main() {
student* list = (student *)malloc(sizeof(student));
char* name = (char *)malloc(sizeof(char));
int age=0;
// inputs for name and age
// do-while(option != EXIT_VALUE);
// inside do-while are the following below
add(&list, name, age);
view(&list);
}
I only get the newest student upon the view method.
It makes sense, since you are allocation space for 1 single student structure:
You should do something like:
The
namevariable suffers from the same problem.A dynamic linked list should have a reference to the next and previous elements. You’ll have to change your program to work with: