Re: void *
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Thu, 28 Jun 2007 07:53:06 +0100
Roman Mashak wrote, On 28/06/07 21:35:
"Barry Schwarz" <schwarzb@xxxxxxxxx> wrote in message news:2cd683lech1rbc5v2vvd1jfvth7j9tug70@xxxxxxxxxxstruct list_nodeIt would probably help if your structure had a member which identified
struct list_node *next;
the real type of whatever data pointed to.
But the structure can't have members for all possible types. And I expected 'void *' is to hold _pointers_ on the objects of various types (perhaps I wasn't very clear in my original post), i.e. I could you something like this:
node *p = NULL;
list_add_head(&p, (int *)100);
This is *not* getting a pointer to an int, it is coercing an int in to an int pointer. There is no guarantee that all int values can be converted to pointers.
list_add_head(&p, (char *)'X');
This is converting another int (not char), this time to a pointer to char. Same problem.
That was my understanding of 'void *' concept.
The concept of void* is what you described in your text, *not* what you show in your code. I.e.
p = &i;
p = &c;
Note that it does *not* require a cast.
In fact at your level the first thing you should assume when you appear to need a cast is that you have done something wrong and a cast is *not* the solution. If it appears that you have not done anything wrong then your next assumption should be that you have completely misunderstood something fundamental and done something very wrong.
There are a few places where casts are required, but not in general where you would expect.
typedef struct list_node node;n->data is a void*. data is a void*. What do you think the cast
node* list_add_head(node **head, void *data)
node *n= malloc(sizeof *n);
/* check if n==NULL ...*/
n->data = (void *)data; /* is that correct use? */
So, n->data = data is enough?
When two variables are of the same type of *course* it is.
Personally I don't think you understand the concept of pointers yet, so you need to read the sections of your text book and the comp.lang.c FAQ that refer to pointers. The comp.lang.c FAQ is available at http://c-faq.com/
- Prev by Date: Re: K&R hash table question
- Next by Date: Re: void *
- Previous by thread: Re: void *
- Next by thread: Re: void *