I'm working on a homework assignment for CS1, it's supposed to bring us back up to speed if we had forgotten some of our C (it's mostly about pointers and memory allocation). I've been working on it for well over 15 hours and I am in need of some serious help.
The problem tells us to use a struct as follows:
typedef struct LottoPlayer {
char first[20];
char last[20];
int nums[6];
} KBLP;
We are supposed to read a file and dynamically allocate memory for an array of these structures, and then we can use that information to select winners yada yada. Whenever I ran my code, I kept getting junk back. So this is what I have, I think the issue is my pointer arithmetic or the way I have set up my malloc.
int main() {
//Code to open the files
int NumTickets;
fscanf(infile, "%d", &NumTickets);
KBLP *size=malloc(NumTickets*sizeof(KBLP));
And then, when I'm reading the file and writing it to the array, I do
int index;
int i;
for (index=0; index < NumTickets; index++) {
fscanf(infile, "%s", size[index].last);
fscanf(infile, "%s", size[index].first);
for (i=0; i<6; i++) {
fscanf(infile, "%d", size[index].nums[i]);
}
}
Now, I feel like I'm missing some dumb here, because when I debug and try to access the size[index].first and things of that nature, I get back garbage memory. Am I not allocating it correctly? Am I not writing to it correctly? Or both?