error creating dynamic memory for a structure. C
Go to solution
Solved by Unimportant,
First of all, you can create a array of 12 char's straight in the struct definition, that saves you a malloc, a free, and a potential leak:
typedef struct { int score; int time; char name[12]; }HighScore;
Secondly, you pass a pointer to the highScore pointer to your function, in order to use the highScore pointer itself you must first dereference the pointer to the highScore pointer:
int getHighScore(HighScore **highScore,int *records) { .... int nr=0; //* dereferences the pointer to HighScore pointer, so you have acces to highScore pointer *highScore=malloc(sizeof(HighScore)*10);//to have memory for 10 records while(!feof(highScoreTable)) { //Following line is no longer needed, because of the change we made to the struct... //highScore[nr]->name=malloc(sizeof(char)*12);// so that name would have memory for 12 chars //highScoreTable is a FILE* fscanf(highScoreTable,"%d %d %s\n",&(*highScore)[nr].score ,&(*highScore)[nr].time, (*highScore)[nr].name); nr++; } .... }
The fscanf line is complex so let's go over it in more detail:
//highScore is a pointer to a HighScore pointer and we want to get pointers to the members to pass to fscanf... //First , we need to dereference the pointer to pointer to get access to the pointer: *highScore //Then, we need to index the array: (*highScore)[nr] //Because [] also dereferences the pointer we need to access the members using . , not -> (*highScore)[nr].score //But we need the address of this member, not the member itself: &(*highScore)[nr].score //But, member name is a array, array names decay into a pointer so we do NOT need to take it's address: (*highScore)[nr].name //<-- note the missing &
And now have a drink to soothe your brain
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now