I created a struct of student inside the function using malloc and populated it with data. I want to return the address of the array of struct back to main and print it line by line, but with my implementation, it is not printing. I debugged my code and indeed, it is able to return the address of my array to main. I don't know why it's not printing though. Any thoughts?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student Student;
struct student
{
char name[100];
int age;
char sex;
};
Student **getstudents(int n)
{
Student **t = malloc(sizeof *t * n); // memory for the array of pointers
for (int i = 0; i < n; i++) // memory for each individual pointer
{
t[i] = malloc(sizeof **t);
}
/* Data is inputted by user with form <student> <sex> <age>, then get mapped to the struct *t */
return t; /* Pointer to an array of pointers */
}
int main()
{
Student **students;
int n;
scanf("%d\n", &n);
students = getstudents(n);
for (int i = 0; i < n; i++)
{
printf("Name: %s, Sex: %s, Age: %d\n", students[i]->name, students[i]->sex, students[i]->age);
}
for (int i = 0; i < n; i++)
{
free(students[i]);
}
free(students);
return 0;
}
I am only allowed to modify the code in `Student **getstudents(int n)`.
Student **fromgetstudents(), while it is in fact returningt, which is aStudent *, so the problem most likely goes that way.getstudentssays it is returning aStudent **but it is returning aStudent *. Change it toStudent *getstudents(int);Student **getstudents(int n)and not their parameters. Does that mean I should change my first line inStudent **getstudentsto a**tinstead of a*t?