skip to Main Content

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


  1. The problem is that you’re attempting to read data into NULL buffers:

    typedef struct
    {
        char* firstname;
        char* lastname;
    

    Try allocating the buffers statically with this small change and the program should be fixed:

    typedef struct
    {
        char firstname[100];
        char lastname[100];
    
    Login or Signup to reply.
  2. In this code:

    typedef struct
    {
        char* firstname;
        char* lastname;
        unsigned int id;
        unsigned int gpa;
    } STU;
    

    firstname and lastname are pointers, but in your case they are not initialised to point to anything.

    You should instead either declare them as arrays:

    #define MAX_NAME_LEN 64 // or something else
    typedef struct
    {
        char firstname[MAX_NAME_LEN];
        char lastname[MAX_NAME_LEN];
        unsigned int id;
        unsigned int gpa;
    } STU;
    

    or you would need to use malloc() or similar to allocate memory for them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search