Re: Problem with Generic Pointers
On Fri, 02 Jun 2006 12:49:06 -0700, "codergem 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;
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));
why not "new gnode;" ?
temp->data=malloc(size);
for(int i=0;i<size;i++)
*(char *)(temp->data+i) = *(char *)(data + i);
why not memcpy?
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 .
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
And you'll have much bigger problems as soon as you attempt to use
anything other than PODs (Plain Old Data types) in your list. It's not
safe to memcpy (or mem-anything) a full class. As an example, frequently
std::strings do not contain their data directly, but hold a pointer to the
data. If one attempted to use your list to store std::strings, very bad
things will happen. Your code will attempt to do a shallow copy of the
std::string, which means that the contained pointer in the string would be
copied, but not the data. Then when your original string goes out of
scope, it will deallocate the memory it had allocated for its data. But
your container's "copy" of the string will still have a pointer to this
deallocated data, which means that if you try to use that string later on,
you'll be invoking Undefined Behaviour.
Now, out of curiosity: why aren't you using std::list<> which has already
solved all of these problems?