When I try to update a pointer inside a struct, I get Segmentation fault when excuting the update function, I don't get the error when executing the print function.
Any help would be appreciated.
Here is the code:
// the struct interpretation contains a dynamic array of variables(boolean values) ex : variables[i] is the value of the variable(i+1)
typedef struct {
bool * variables;
int number_of_var;
} INTERPRETATION;
INTERPRETATION * INTERPRETATION_create();
void INTERPRETATION_update(INTERPRETATION *,int,bool);
void INTERPRETATION_print(INTERPRETATION);
int main()
{
INTERPRETATION *inter=INTERPRETATION_create();
INTERPRETATION_print(*inter); // works fine
// by default an uninitialised bool variable takes false as an initial value
// so all the values in the array inter->variables are false
INTERPRETATION_update(inter,2,true); // a Segmentation fault
return 0;
}
INTERPRETATION * INTERPRETATION_create(){
INTERPRETATION inter;
INTERPRETATION *ptr;
inter.number_of_var=4;
inter.variables=(bool*) malloc(inter.number_of_var * sizeof(bool));
ptr=&inter;
return ptr;
}
void INTERPRETATION_update(INTERPRETATION *inter,int var,bool value){
inter->variables[var-1]=value; // a Segmentation fault
}
void INTERPRETATION_print(INTERPRETATION inter){
int i=0;
for (i;i<inter.number_of_var;i++ ){
printf("variable%d=",(i+1));
printf(inter.variables[i] ? "true\n" : "false\n");
}
}