DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Pointer arrays and structures (http://www.daniweb.com/forums/thread159895.html)

OutOfReach Nov 28th, 2008 2:59 pm
Pointer arrays and structures
 
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?

mahlerfive Nov 28th, 2008 3:51 pm
Re: Pointer arrays and structures
 
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) );

OutOfReach Nov 28th, 2008 4:15 pm
Re: Pointer arrays and structures
 
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. :)


All times are GMT -4. The time now is 7:36 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC