I am curious why this code works:
typedef struct test_struct {
int id;
} test_struct;
void test_func(test_struct ** my_struct)
{
test_struct my_test_struct;
my_test_struct.id=267;
*my_struct = &my_test_struct;
}
int main ()
{
test_struct * main_struct;
test_func(&main_struct);
printf("%d\n",main_struct->id);
}
This works, but pointing to the memory address of a functions local variable is a big no-no, right?
But if i used a structure pointer and malloc, that would be the correct way, right?
void test_func(test_struct ** my_struct)
{
test_struct *my_test_struct;
my_test_struct = malloc(sizeof(test_struct));
my_test_struct->id=267;
*my_struct = my_test_struct;
}
int main ()
{
test_struct * main_struct;
test_func(&main_struct);
printf("%d\n",main_struct->id);
}