Search code examples
cfile-iostructure

C language - structure


When execute second fscanf, console stop working. What did I do wrong?

The input file contains:

3
minsu 50 80 40
sarah 30 60 40
jason 70 80 90

The code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct studentT {
    char *name;
    int literature;
    int math;
    int science;
}studentT;

int main()
{
    studentT student[3];
    int count;
    char *inputFileName = malloc(sizeof(char)*30);
    char *outputFileName = malloc(sizeof(char) * 30);
    float avg;
    int i = 0;

    scanf("%s %s", inputFileName, outputFileName);

    FILE *fp = fopen(inputFileName, "r");

    if (fp == NULL)
    {
        printf("file is not exist");
        return 1;
    }

    fscanf(fp, "%d", &count);

    for (i = 0; i < (int)count; i++)
    {
        //printf("!");
        fscanf(fp, "%s %d %d %d", student[i].name, &student[i].literature, &student[i].math, &student[i].science);
        //printf("2");
        printf("%s %d %d %d\n", student[i].name, student[i].literature, student[i].math, student[i].science);
        //printf("333\n");
    }

    fclose(fp);
    free(inputFileName);
    free(outputFileName);
    return 0;

}

Solution

  • The name field in your studentT struct is a char *. You pass that pointer to scanf without initializing it to anything. So scanf reads an uninitialized pointer and tried to dereference it. This invokes undefined behavior.

    The simplest way to fix this is to change name to be an array large enough to hold any string you expect. Then you can write to the array:

    typedef struct studentT {
        char name[20];
        int literature;
        int math;    
        int science;
    }studentT;
    

    Alternately, you can use malloc to allocate space dynamically:

    student[i].name = malloc(20);
    fscanf(fp, "%19s %d %d %d", student[i].name, &student[i].literature, 
                                &student[i].math, &student[i].science);