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:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _struct {char *str;};
void allocate_and_initialize(struct _struct *s)
{
s = calloc(sizeof(struct _struct), 1);
s->str = 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;
}
You are passing
sby value. The value ofsis unchanged in main after the call toallocate_and_initializeTo fix this you must somehow ensure that the
sin main points to the memory chunk allocated by the function. This can be done by passing the address ofsto the function:Alternatively you can return the address of the chunk allocated in the function back and assign it to
sin main as suggested in other answer.