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
In your example:
void allocate_and_initialize(struct _struct *s)
{
s = calloc(sizeof(struct _struct), 1);
s->str = calloc(sizeof(char), 12);
strcpy(s->str, "hello world");
}
Assigning to s here doesn't change s in the caller. Why not return it instead?
struct _struct *allocate_and_initialize(void) {
struct _struct *s;
s = calloc(sizeof *s, 1);
s->str = calloc(1, 12); /* sizeof(char) is always 1 */
strcpy(s->str, "hello world");
return s;
}
and use it thus:
struct _struct *s;
s = allocate_and_initialize();
/* use s... */
free(s); /* don't forget to free the memory when you're done */