Copying a struct

Started by
2 comments, last by Afr0m@n 18 years, 4 months ago
How do I do this? I think I've gathered enough knowledge about pointers and such by now to be able to make a linkd list system. But I'm still struggling with making the system dynamic. I can't post the code I've made so far, because I'm on my dad's comp right now cos the internet is down on mine. But what I have in a listnode is a pointer to the next structure and a pointer that's meant to point to any type of struct. The latter one being a void pointer, obviously. See - no matter how many tutorials I find, I can't seem to find one where it is explained how to copy data from a pointer into a memory area (using malloc?) and then making the pointer in a listnode point to that data (so the linked list becomes truly dynamic because each node can contain any type of data). I tried a doing this yesterday for a couple of hours (using malloc), but no matter what I did I just ended up with "Illegal indirection" style errors and the like. I know how to make a memory area using malloc and assigning the resulting adress to a pointer, but I can't figure out how to actually copy data from one adress to another (not just the adresses themselves - that is easy). Has anyone got any clues?
_______________________Afr0Games
Advertisement
If you are writing a linked list that uses a void pointer to store data, you don't actually want to copy the object. What you should be doing is pointing the void* at the stucture passed in, not copying the structure passed in to the void*.
To copy memory, you have to use the memcpy function, but I don't think that is really a solution to your problem.
Also, making a linked list "truly dynamic" by using a void* like you mentioned isn't really a good idea. You could use a templated node class in your linked list, but generally a linked list should only contain one type of object.
there are varoius ways to copy memory from one place to another.
here are some of them:

typedef struct
{ int somedata;
float someanotherdata;
char somearray[128];
} somestruct;


void copy_memory(void *somepointer)
{ somestruct newdata;
//
// method#1 cast the pointer,
//
data = *((somestruct*)somepointer);

//
// method#2 use memcpy
//
memcpy(&newdata,somepointer,sizeof(data));

//
// method#3 do it youself...
//
char *src = (char*)somepointer;
char *dst = (char*)&newdata
int t;
for(t=0;t<
Thanks the_dannobot! :D Yes, I thought about that, but in my mind, that doesn't work. Because that assumes that all the data in each node will remain unchanged because each data pointer is pointing to the same struct! So, instead of a system where you change a piece of data and update the entire system, I want a system where each node can be updated separately.

Edit: Thanks to you too, anonymous poster! :) Always great to see how to do things. :)
_______________________Afr0Games

This topic is closed to new replies.

Advertisement