initialization - Passing a pointer to a pointer vs passing a pointer for initialisation in C -
i have data structure, linked list, looks like
struct listitem { void* data; struct listitem* next; }; typedef struct listitem listitem; typedef struct { listitem* head; pthread_rwlock_t lock; } linkedlist;
i using pointer void* data because want make data structure polymorphic can use few different applications.
to initialise list (allocate memory , initialise rw lock), pass function init_list(..). when pass pointer list follows, program hangs whenever try , perform further operations on list (e.g. push item it):
int init_list(linkedlist* list /* borrowed - list initialise (probably unallocated) */) { list = (linkedlist*)calloc(1, sizeof(linkedlist)); // clear memory, head null pointer printf("allocated memory\n"); if (list == 0) { perror("calloc failed on allocating memory list"); return 1; } printf("initialising lock\n"); pthread_rwlock_init(&list->lock, null); return 0; } ... linkedlist* ll; init_list(ll);
it understanding above should clear memory pointed ll , initialise memory location of lock appropraitely.
when pass pointer pointer list, however, works fine (i.e. program doesn't hang when try , perform further operations acquiring lock , pushing item list). don't see why adding layer of indirection makes work. i'd have thought operations on actual memory locations same, regardless of how referred them?
i.e. following works, whereas first approach doesn't:
int init_list(linkedlist** list /* borrowed - list initialise (probably unallocated) */) { *list = (linkedlist*)calloc(1, sizeof(linkedlist)); // clear memory, head null pointer printf("allocated memory\n"); if (list == 0) { perror("calloc failed on allocating memory list"); return 1; } printf("initialising lock\n"); pthread_rwlock_init(&(*list)->lock, null); return 0; } ... linkedlist* ll; init_list(&ll);
i can't explain why second approach works when first doesn't.
in terms of general style, approach common? or there better, more common way of initialising data structures in c? i'm relatively new c programmer , come object oriented languages, i'd expect such initialisation in constructor, , i'm kind-of trying copy style in c, - thinking - may not logical?
in first case pushed copy of pointer (ll) onto stack. code allocates memory, presume sizeof(slinkedlist)
typo, fills 0,....and discards copy. caller never gets updated pointer back. print value of ll
after init. in second one, push pointer pointer, gets allocated/initialised , when return caller can happily use it. can go first version if instead of returning 0 or 1 return ll
, assign return value variable in caller. kind of functional style.
Comments
Post a Comment