How can I allocate memory for a struct pointer and assign value to it\'s member in a subfunction?
The following code will compile but not execute:
#i
you must change your code like that:
#include
#include
#include
struct _struct {char *str;};
void allocate_and_initialize(struct _struct **s)
{
*s = (_struct*)calloc(sizeof(struct _struct), 1);
(*s)->str = (char*)calloc(sizeof(char), 12);
strcpy((*s)->str, "hello world");
}
int main(void)
{
struct _struct *s;
allocate_and_initialize(&s);
printf("%s\n", s->str);
return 0;
}
The reason is, that you change the adress of the pointer, but not the "content" of the pointer. So, if you code in c, you have to use a "double" pointer. If you code in c++ you can use a reference.