Helo !!!
I was trying to implement linked list in which the data field is
Generic...
the structure details are..

typedef struct node 
 { 
         void *data; 
         struct node *next; 
 
 }gnode;

Now to add a node into it, and i have written this function.

void insert(gnode **head,void *data,unsigned int size) 
 { 
         gnode *temp; 
         int i=0; 
         temp=(gnode *)malloc(sizeof(gnode)); 
         temp->data=malloc(size); 
         for(int i=0;i<size;i++) 
                 *(char *)(temp->data+i) = *(char *)(data + i); 
 
         temp->next= (*head); 
         (*head)=temp; 
 
 }

Well i dont know how to copy the data into the temp->data.
But I m trying the following code...
for(int i=0;i<size;i++)
*(char *)(temp->data+i) = *(char *)(data + i);

But it is giving the error :sad:: ' void * ' : Unknown size .

If anyone knows any other way of copying it please tell me. And please
help me out in finding what is happening wrong in this code.
Thanks:-|

One word: memcpy.

Thanks.
I have tried using memcpy, but i wanted to know to rectify the bugs in the present logic.
I want to copy the data using for loop.If you could help me in this, then your suggestions are welcome.
And memcpy will be not working with strings as input. Help me in this regard also.

>i wanted to know to rectify the bugs in the present logic.
Okay, look at the code:

*(char *)(temp->data+i) = *(char *)(data + i);

Pointers to void have no size, therefore they cannot be scaled. You need to cast a pointer to void to a pointer to something else first, then scale the result and finally dereference:

cast:    (char*)temp->data      =   (char*)data
scale:  (                  + i)    (            + i)
deref: *                          *
final: *((char*)temp->data + i) = *((char*)data + i);

>And memcpy will be not working with strings as input.
Don't make me beat you with the grammar bat. memcpy works just as well with non-string data as it does with string data. Whatever you pass it is converted to a pointer to void, then treated as an array of unsigned char. That's why you pass a byte count rather than an item count as the last argument.

>And memcpy will be not working with strings as input.
Oooopsss!!!! srry this last line was a complete blunder.
and Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.