c - Making a void* within a struct point to an integer -
i have struct follows:
typedef struct node { void* data; unsigned long id; nodeptr next; nodeptr prev; } node; it meant node in linked list adt. have 2 different constructors depending on node needs hold in data. 1 constructor uses:
nodeptr tempnode; tempnode = malloc( sizeof(node) ); /* other stuff */ tempnode->data = newlist(); return (tempnode); and seems work fine letting me access list returning (list->current->data) current node pointer in list struct
however, want make version of constructor (data) points int. i've read can doing following
void* ptr; int x = 0; *((int*)ptr) = x; but way constructor set up, mean have this?
*((int*)tempnode->data) = 1; // data starts @ 1 and doesn't work. i'm new c don't understand of terminology. read dereferencing (using -> notation?) cannot done void*'s, seems work fine in list version of constructor. how can rewrite other constructor cast void* int?
i counsel against doing this, if want use void * member hold integer, can do:
node *constructor_int(int n) { node *tmp = malloc(sizeof(*tmp)); /* other stuff */ tmp->data = (void *)n; return(tmp); } this involves minimum number of casts , avoids problems relative sizes of types.
the obvious, logical way allocate integer data member point at:
node *constructor_int(int n) { node *tmp = malloc(sizeof(*tmp)); /* other stuff */ tmp->data = malloc(sizeof(int)); *(int *)temp->data = n; return(tmp); } you have remember free 2 memory allocations.
the code should check memory allocations succeeded before using results.
Comments
Post a Comment