c - Making linked list more generic -


could me understand void pointers using linked list.

i have:

struct listnode {     int nodevalue;     struct listnode * next; };  typedef struct listnode listnode; 

which works ints. if change int nodevalue void *nodevalue, how send values linked list using void pointer instead?

for instance, had add front function:

void addfront(listnode *l, int number); 

which takes listnode , number.

if void* pointer, change signature to:

void addfront(listnode *l, void* value); 

in main function using ints have like:

int main(void) {        listnode *list;     list = createlist();      (int x = 0;x < 8;x++)     {         addfront(list,x);      }      return(0); } 

where createlist defined as:

listnode *createlist() {     listnode *anynode;     anynode = malloc(sizeof(listnode));     anynode->next = null;     return anynode; }  listnode *initnode(int number) {     listnode *newnode;     newnode = malloc(sizeof(listnode));     newnode->nodevalue = number;     newnode->next = null;     return(newnode); } 

to make list more generic, how pass integers using void* instead of declaring integer.

unfortunately, kind of generic behavior comes @ price of large overhead: in order save int on list need extend scope allocating int dynamically:

listnode *initnode(int number) {     listnode *newnode;     newnode = malloc(sizeof(listnode));     newnode->nodevalue = malloc(sizeof(int));     *(newnode->nodevalue) = number;     newnode->next = null;     return(newnode); } 

this increases memory requirements many times, because malloc(sizeof(int)); typically allocates @ least 16-byte block.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo