The problem is the insert method in the line of code you marked in the question
sample->p[sample->id]->name = _name;
Nowhere in your program do you allocate memory for the p array inside the person structure. Therefore, this value will always be NULL . Attempting to assign this value rightfully will cause your program to crash.
To fix this, you need to make sure that the p array is large enough to place the index provided by the expression sample->id . The best way to achieve this is to use the realloc function and add a field in person to store the size of the p array
Here is a quick example. Note. Verification error and 0 memory initialization omitted for bevity.
struct person{ struct element** p; size_t length; int id; }; void insert(struct person* sample, char* _name, int _age) { if (sample->id >= sample->length) { sample->p = realloc(sample->p, sizeof(element*) * sample->id); } ... }
It seems strange, although the name and age are always indexed through the sample->id field. This means that it always fits in the same place, in which case the array is not needed. Can you talk about how this should work?
source share