Double indirection and structures passed into a function
Posted
by ZPS
on Stack Overflow
See other posts from Stack Overflow
or by ZPS
Published on 2010-03-30T21:14:36Z
Indexed on
2010/03/30
21:23 UTC
Read the original article
Hit count: 247
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);
}
© Stack Overflow or respective owner