c - Segmentation fault: 11 when returning stuct via function pointer in struct -
i'm trying emulate constructor. i'm attempting having parent struct have function pointer returns pointer child struct. appreciated.
#include <stdio.h> #include "stdlib.h" typedef struct child_t { char *name; } child; typedef struct parent_t { child (*newchild)(); } parent; child *newchild() { child *child = malloc(sizeof(child)); child->name = "foo"; return child; } int main() { parent parent; child child = parent.newchild(); }
i think mean following
#include <stdio.h> #include <stdlib.h> typedef struct child_t { char *name; } child; typedef struct parent_t { child * ( *newchild )( void ); } parent; child * newchild( void ) { child *child = malloc( sizeof( child ) ); child->name = "foo"; return child; } int main( void ) { parent parent = { newchild }; child *child = parent.newchild(); puts( child->name ); free( child ); }
the program output
foo
that should declare function correctly. return type must pointer. must declare function pointer correctly in structure definition
typedef struct parent_t { child (*newchild)(); ^^^^^^ } parent;
and need initialize object of type parent.
parent parent = { newchild };
otherwise has indeterminate value.
Comments
Post a Comment