void pointer



Hello,

I'm studying linked lists and implemented the following:

struct list_node
{
void *data;
struct list_node *next;
};

I intentionally defined 'void *' for data field in order to use various
types. Here is a function adding element to linked list:

/* add element in the beginning of list */
static list *list_add(list **p, void *data)
{
list *n = malloc(sizeof(list));
n->next = *p;
*p = n;
n->data = (void *)data;
return n;
}

My question is: is this valid type casting

n->data = (void *)data;

Will I be able to add 'data' of 'int', 'long', 'char' etc. types? Is this
right approach?

Thank you.

--
Best regards, Roman


.



Relevant Pages

  • Re: void pointer
    ... I'm studying linked lists and implemented the following: ... struct list_node *next; ... I intentionally defined 'void *' for data field in order to use various types. ... Or use a union: ...
    (comp.lang.c)
  • Re: Nested linklist
    ... this is to augment the struct with a `next' pointer: ... kind of struct that keeps track of useful information about ... we've started from a struct with some payload ... individual nodes are linked lists as above. ...
    (comp.lang.c)
  • Re: Want to optimize this procedure, any advice?
    ... Creating functions for doubly linked lists, ... void InsertLink(CONTACT **root, CONTACT *src); ... CONTACT *FileToList(const char *filename); ...
    (comp.lang.c)
  • Re: Generic linked list with internal storage?
    ... list package is about as useful as a generic array package. ... Just stick a `struct node *next' ... If you've got a lot of linked lists of a lot of disparate ... The principal benefits of generic "containers" are, IMHO, ...
    (comp.lang.c)
  • Re: Dynamically growing an array (pointer question)
    ... > pointers to a struct Atom. ... array of pointers to linked lists can be tricky. ... void PrintLINK; ... int ReallocScreen; ...
    (comp.lang.c)