c - First time working with opaque pointers -
i trying implement stack, not understanding use of opaque pointer. here declaration:
/* incomplete type */ typedef struct stack_t *stack; /* create new stack, have call first */ stack new_stack(void);
and here stack structure , new_stack function:
struct stack_t { int count; struct node_t { void *data; struct node_t *next; } *head; }; stack new_stack(void) { struct stack_t new; new.count = 0; new.head->next = null; return new; }
in eyes, returning address of new stack, throws error on compilation returning new. doing wrong?
you returning stack_t
value, return type of stack_new
function stack
, typedef struct stack_t* stack
.
need return pointer - change allocation of stack_t
stack heap use malloc
dynamic allocation.
don't remember free()
stack when not needed anymore, because dynamically allocated.
stack new_stack(void) { struct stack_t* new = malloc(sizeof(struct stack_t)); new->count = 0; new->head = null; return new; }
Comments
Post a Comment