Re: Problem with Generic Pointers
codergem@gmail.com wrote:
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;
That looks like a pretty useless thing to me: you cannot safely store items
of different types in this list (i.e., you cannot use it as a heterogenous
container) because there is no way to retrieve the type for an individual
item wherefore casting back the data to a correct type becomes impossible.
Now, for a homogenous container, you could just use std::list.
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 have written the following code...
for(int i=0;i<size;i++)
*(char *)(temp->data+i) = *(char *)(data + i);
But it is giving the error : ' void * ' : Unknown size .
The problem is that you cannot use pointer arithmetic on void*. Replace all
occurrences of void* with unsigned char* and you will be fine, i.e., the
code will be horrible but it should compile:
struct gnode
{
unsigned char * data;
struct gnode * next;
};
void insert( gnode* & head, unsigned char* data, unsigned int size )
{
gnode* temp = new gnode;
temp->data = new unsigned char [ size ];
for( unsigned int i=0; i < size; ++i ) {
temp->data[i] = data[i];
}
temp->next = head;
head = temp;
}
As you can see, I did a few other changes to make it look more like C++.
Also, please note that this code is not exception safe: if the second new
throws, the memory allocated by the first new leaks.
Best
Kai-Uwe Bux