Search code examples
cpointersfgetsgets

How can I use a Pointer to structure in C?


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.\n\n", 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:\Practice\P_22\Project22\x64\Debug\Project22.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.


Solution

  • 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.