Andrew
Andrew

Reputation: 9

Homework: C Programming - Structures and Arrays

My assignment requires the use of the following linked list structure:

      struct studentNode {
        int     id;
        char    *fname;
        char    *lname;
        int     programs[x];
        int     labs[x];
        int     exams[x];
        int     percent;
        double  grade;

        struct  studentNode *next;
      };

My problem is, the arrays for programs, labs and exams are being loaded from a file and are to be variable lengths.

I tried using a pointer to the array, however whenever I updated the array for a new student it would replace the scores for everyone in the linked list.

I've tried going over this with the instructor and he tells me to google it. :(

So far, I haven't had any luck and it's beyond the scope of what our book covers.

Any help would be appreciated.

Upvotes: 0

Views: 941

Answers (4)

user623879
user623879

Reputation: 4142

It sounds like you are using the same array for all students. You need to allocate a separate array for each student.

You can either statically allocate a fixed number of elements in a 2d array:

int progs[Num_students][x];

In this case you will need to point each studentNodes array to the correct array(for each student).

studentNode1.programs = progs[studentNumber];

Or allocate some memory on the heap for each student.

studentNode1.programs = malloc(sizeof(int)*x);

Upvotes: 0

amccormack
amccormack

Reputation: 13927

I believe your question is referring to how to specify the size of the programs, labs, and exams arrays.

Instead of storing the array in your struc, keep a pointer to your array. Then, after you have built your program array outside of your structure (using malloc if necessary) reassign your node.program pointer to that array.

Upvotes: 0

dappawit
dappawit

Reputation: 12590

Make sure each studentNode isn't sharing the same programs, labs, etc arrays. In addition to creating the studentNode, you have to create the arrays within them.

Upvotes: 0

Preet Sangha
Preet Sangha

Reputation: 65536

From what you describe:

You need to create a new object for each item in the array.

so first you create something to hold the first item (like a pointer to the first item). Then as you load each item, create new studentNode and then add it to the array.

Upvotes: 2

Related Questions