'How to free a struct array in C
I have a struct array like this
typedef struct {
char *name[50];
int score;
} score;
Memory is allocated to that array like this
score *scores = (score *) malloc(sizeof(score) * size);
I need to do an if-check and regarding to that check I am deallocating that memory space. So right now, I have 2 questions in my mind
- Why can't I just free-up space like this ?
for (int i = 0; i < size; i++) {
if (scores[i].score == scoreToBeDeleted) {
free(scores[i].name);
free(&(scores[i].score));
free(&(scores[i]));
}
}
- Should I shift the elements of the array as I remove records ?
Solution 1:[1]
You can't deallocate your struct variables because you haven't allocated them explicitly, you have allocated the array of struct scores.
/* Allocate scores */
scores *scores[size];
for (size_t i = 0; i < size; i++) {
/* Allocate scores individually */
scores[i] = (score *) malloc(sizeof score);
}
/* Deallocate scores */
for (int i = 0; i < size; i++) {
if (scores[i]->score == scoreToBeDeleted) {
free(scores[i];
}
}
This way you can achieve your desired behavior. Or you could use linked list of scores.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vaizq |
