I’m trying to work through Kernighan’s book “C Programming Language” to teach myself C in preparation for a data structures class this spring (C is a required prerequisite), but am stuck on how to deal with multiple structures and how you would store multiples to use later for calculations and output. I wrote some code for structures related to student records with variables for id’s and scores which follows. The function names and parameters must stay as is and comments describe what should be done by each function.
So here’s what I’ve tried. I thought of just setting up an array of structures for ten students within the allocate function as follows:
struct student s[10];
However, when I try to return it to main and then pass it to the generate function, I get incompatibility errors. My current efforts are below. However, as you can see, my code fails to store anything but the last set of records (i.e. student.id and student.score) generated. Clearly I’m missing a key component and it’s preventing me from being able to generate random unique student id’s because I can’t check a new id against the previous ones. I also can’t move forward in writing functions to run calculations on student scores. Any suggestions would be appreciated. Thanks in advance.
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
#include<assert.h>
struct student{
int id;
int score;
};
struct student* allocate(){
/*Allocate memory for ten students*/
struct student* s = malloc(10 * sizeof(struct student));
assert (s != 0);
/*return the pointer*/
return s;
}
void generate(struct student* students){
/*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
int i;
for (i = 0; i < 10; i++) {
students -> id = (rand()%10 + 1);
students -> score = (rand()%(100 - 0 + 1) + 0);
printf("%d, %d\n", (*students).id, (*students).score);
}
}
void deallocate(struct student* stud){
/*Deallocate memory from stud*/
free(stud);
}
int main(){
struct student* stud = NULL;
/*call allocate*/
stud = allocate();
/*call generate*/
generate(stud);
/*call deallocate*/
deallocate(stud);
return 0;
}
Change generate to