I have a problem in which there is a struct that will hold the name, age and student id. I have to take an input from the user and make that number of structs without using any array notation. And then each of the struct's parameters should be taken input from the user and printed at the same time. It is like creating a database of students. The struct is:
typedef struct
{
char *name;
char *std_id;
int age;
} student;
So my input would be like :
Number of students: 3
Name of the student1: Bro
std_id of the student1: 46845
age of the student1: 18
Name of the student2: kim
std_id of the student2: 46867
age of the student2: 19
Name of the student3: Sean
std_id of the student3: 46862
age of the student3: 18
And the output would be like:
Name of the student1 is: Bro
std_id of the student1 is: 46845
age of the student1 is: 18
Name of the student2 is: kim
std_id of the student2 is: 46867
age of the student2 is: 19
Name of the student3 is: Sean
std_id of the student3 is: 46862
age of the student3 is: 18
The main problem is we can't use any array in this problem.
What I tried coding the problem by searching the internet is this code:
#include<stdio.h>
#include<string.h>
typedef struct
{
char *name;
char *std_id;
int age;
} students;
int main()
{
int num;
printf("Type the number of students:");
scanf("%d", &num);
students* ptr = malloc(num * sizeof(*ptr));
if(ptr == NULL)
{
printf("memory not free!");
return 0;
}
for(int i=0; i<num; i++)
{
printf("\nGive the name of the std %d:", i+1);
(ptr+i)->name = malloc(sizeof(char)*20);
if((ptr+i)->name == NULL)
{
printf("memory not free!");
return 0;
}
scanf("%s", (ptr+i)->name);
printf("Give the std_id of the std %d:", i+1);
(ptr+i)->std_id = malloc(sizeof(char)*10);
if((ptr+i)->std_id == NULL)
{
printf("memory not free!");
return 0;
}
scanf("%s", (ptr+i)->std_id);
printf("Give the age of std %d:", i+1);
scanf("%d", (ptr+i)->age);
}
for(int i=0; i<num; i++)
{
printf("\nThe name of the std %d: %s", i+1, (ptr+i)->name);
printf("\nThe std_id of the std %d: %s", i+1, (ptr+i)->std_id);
printf("\nThe age of the std %d: %d", i+1, (ptr+i)->age);
}
return 0;
}
Using this code, this is what my console looks like:
Type the number of students:3
Give the name of the std 1:Sean
Give the std_id of the std 1:45
Give the age of std 1:23
Process returned -1073741819 (0xC0000005) execution time : 23.131 s
Press any key to continue.
Here I am trying to first run the code for name
variable. If that runs correctly, I'll implement the other variables like name
variable. But when I run this code the the program exits after taking just one input. I just can not figure out the problem by my own. Any help on how to tackle this problem will be highly appreciated.