Hey all, I am a C beginner. My problem with my code is that I get a segfault.
Here's my code

#include <stdio.h>

struct studentInfo {
    int totalClasses;
    float GPA;
    char studentName[41];
};


main()
{
    int numOfStudents, i;
    printf("How many students would you like to take account of? ");
    scanf(" %d", &numOfStudents);

    struct studentInfo *students[numOfStudents-1];

    for (i=0; i < numOfStudents; i++)
    {
        printf("Enter the total number of the student's classes: ");
        scanf(" %d", &students[i]->totalClasses);

        printf("Enter the student's GPA: ");
        scanf(" %f", &students[i]->GPA);
        getchar();  /* Clear the extra keypress in the buffer */

        printf("Enter the student's name: ");
        fgets(students[i]->studentName, 41, stdin);
        printf("\n\n");


    }

    printf("\n\n");

    for (i=0; i < numOfStudents; i++)
    {
        printf("Student Name: %s", students[i]->studentName);
        printf("Student GPA: %.3f\n", students[i]->GPA);
        printf("Number of Student Classes: %d\n\n", students[i]->totalClasses);
    }
    printf("\n\n");

    printf("Goodbye.\n");

    return 0;
}

According to gdb the segfault happens on:

scanf(" %d", &students[i]->totalClasses);

But I don't know what I am doing wrong. Any help?

You have allocated space for all of the studentInfo pointers here (except the last one, you should not be subtracting 1):

struct studentInfo *students[numOfStudents-1];

But, you have not allocated space for the actual studentInfo structures that each pointer will point to. To do that you will have to make a loop that allocates a studentInfo for each pointer using malloc().

Something like:

students[i] = (studentInfo*) malloc( sizeof(studentInfo) );

Ahh! I see, so you need to allocate space for each structure that the pointer points to.

I ended up using:

students[i] = (struct studentInfo *)malloc(sizeof(struct studentInfo));

And now everything works fine. Thank you. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.