My goal is to modify data1 and data2 using a function that was passed as an argument from another function. I tried but failed. Here below is my last attempt. Could you please tell me what I am doing wrong?
typedef struct data_structs
{
int data1;
int data2;
} DATA_STRUCT;
int inner_func(void** user_data)
{
DATA_STRUCT *inner_data = (DATA_STRUCT *) (*user_data);
inner_data->data1 = 1;
inner_data->data2 = 2;
return 0;
}
void func(void **user_data, int (*passed_func)(void**) )
{
passed_func( (void**) &user_data );
}
int main(void)
{
DATA_STRUCT *data = malloc(sizeof(DATA_STRUCT));
func( (void**) &data, inner_func );
printf("I expect 1 and 2 %d, %d\n", data->data1, data->data2);
}
CodePudding user response:
As has already been stated in the comments, your problem probably is with the void **
.
Try this code instead (untested):
typedef struct data_structs
{
int data1;
int data2;
} DATA_STRUCT;
int inner_func(void *user_data)
{
DATA_STRUCT *inner_data = (DATA_STRUCT *)user_data;
inner_data->data1 = 1;
inner_data->data2 = 2;
return 0;
}
void func(void *user_data, int (*passed_func)(void *))
{
passed_func(user_data);
}
int main(void)
{
DATA_STRUCT data;
func(&data, inner_func );
printf("I expect 1 and 2 %d, %d\n", data.data1, data.data2);
}
CodePudding user response:
if you want to use a double-pointer, you should initialize your data structure with a pointer.
here's a way to do it, but I didn't test it, so it might have typos or mistakes:
typedef struct data_structs
{
int data1;
int data2;
} DATA_STRUCT;
void inner_func(DATA_STRUCT **inner_data)
{
(*inner_data)->data1 = 1;
(*inner_data)->data2 = 2;
return;
}
void func(DATA_STRUCT **user_data, void (*passed_func)(DATA_STRUCT **))
{
passed_func(user_data);
}
int main(void)
{
DATA_STRUCT *data= (DATA_STRUCT *)malloc(sizeof(DATA_STRUCT));
func(&data, inner_func );
printf("I expect 1 and 2 %d, %d\n", data->data1, data->data2);
free(data);
}