I’m not sure how to explain this but this piece of code bellow can compile perfectly but when you run it, SIGSEV.
Please, can anyone tell precisely where I got things wrong?
The fact is I want to be able to access elements by index as below and at the same time to be able to work with struct.
#include <stdio.h>
#include <stdlib.h>
/* This is a struct describing properties of an element */
struct element{
int age;
char* name;
};
/* This struct contains a pointer to a pointer on a element "struct element" */
struct person{
struct element** p;
int id;
};
/* Thus function initializes a struct person by allocation memory for it */
struct person* init(int size)
{
struct person* sample = (struct person* )malloc(size*sizeof(struct person));
sample->p = NULL;
sample->id = 0;
return sample;
}
/* use this function to insert a new element in the struct */
void insert(struct person* sample, char* _name, int _age)
{
sample->p[sample->id]->name = _name; /* the program crashes here according to the debugger , but why?? */
sample->p[sample->id]->age = _age; /* of course, this will cause trouble too because it has the same construct as the previous one */
sample->id++;
}
/* main entry */
int main()
{
struct person* student = init(10); /* Allocating space for 10 students */
insert(student, "kido", 8);
printf("Your name is %s and your age is %d", student->p[0]->name, student->p[0]->age); /* we can't write student->p->name */
return 0;
}
The problem is in the
insertmethod at the line of code you flagged in the questionNowhere in your program do you allocate memory for the
parray inside of thepersonstruct. Hence this value will always beNULL. Attempting to assign to this value will rightfully lead to a crash of your program.To fix this you need to ensure the
parray is large enough to accommodate the index provided by the expressionsample->id. Best way to accomplish this is to use thereallocfunction and add a field topersonto store the size of theparrayHere’s a quick sample. Note: Error checking and 0 initialization of memory omitted for bevity.
It does seem odd though that the name and age are always indexed via the
sample->idfield. This indicates that it’s always placed in the same location in which case an array is not needed. Can you elaborate on how this is supposed to function?