I have problem with pointer to structure in C.
This is my code :
#include <stdio.h>
#define N 10 // determine the number of students
typedef struct
{
char* firstname;
char* lastname;
unsigned int id;
unsigned int gpa;
} STU;
void stuinfo(unsigned int, STU*);
int main()
{
STU student[N];
printf_s("The number of students is %d.nn", N);
for (unsigned int i = 0; i <= N - 1; i++)
{
stuinfo(N, &student[i]);
}
return 0;
}
void stuinfo(unsigned int stuinfo_n, STU* pstudent)
{
for (unsigned int i = 0; i <= stuinfo_n - 1; i++)
{
printf_s("Enter the first name of student %d : ", i + 1);
fgets(pstudent->firstname, 99, stdin);
printf_s("Enter the last name of student %d : ", i + 1);
fgets(pstudent->lastname, 99, stdin);
}
}
This program runs but does not work properly and gives an error after receiving the first input.
Output :
The number of students is 10.
Enter the first name of student 1 : Jason
D:PracticeP_22Project22x64DebugProject22.exe (process 24068) exited with code -1073741819.
Press any key to close this window . . .
I use Microsoft Visual Studio 2022
I used gets_s() function instead of fgets() function, but the problem was not solved.
2
Answers
The problem is that you’re attempting to read data into
NULL
buffers:Try allocating the buffers statically with this small change and the program should be fixed:
In this code:
firstname
andlastname
are pointers, but in your case they are not initialised to point to anything.You should instead either declare them as arrays:
or you would need to use
malloc()
or similar to allocate memory for them.