Quote:

What you wrote in your original post doesn't work in C or C++ either (not without overloading the assignment operator for your struct, anyway).




It does work. The default behavior for = when it comes to structs and classes is to copy its members. I made a small program and checked it out (even though I was 99% sure before, lite-c confused me ). You can find it here:
http://web.telia.com/~u87309837/forum/C.zip

Quote:

Think about the implications of what you expect this code to do. If using assignment on an arbitrary struct instance would copy it over to the assigned-to struct, it would copy pointers too. What if your struct contains a pointer to some variable that should be allocated per-struct. When you copy that struct, it would copy the pointer, NOT the data pointed-to, so now you have two struct instances sharing the same pointee. Sometimes this is what you want, often it's not. In any case, you must specify what you want to do, so assignment of structs is not implemented in C.

You should copy the elements member by member, or with memcpy as HeelX pointed out.




In this case I want the members to be copied.
And btw, memcpy would cause the same problem with pointers as when using =, wouldnt it? Its not like it magically would know when the user wants it to really copy a pointer or whats stored at the pointed space.

Quote:

Could you show the code where you tried to use memcpy?

BTW, memcpy works on the heap as well as on the stack in C++ (haven't tested with Lite-C, but would be strange if it behaved differently).




Code:
#include <default.c>

typedef struct
{
int member1;
int member2;
} astruct;

//astruct* array[10];
astruct array[10];

function main()
{
// astruct* tmp = malloc(sizeof(astruct));
astruct tmp;
tmp.member1 = 10;
tmp.member2 = 20;

// memcpy(array[0], tmp);
memcpy(array[0], tmp, sizeof(astruct));
// memcpy(&array[0], &tmp);?
}



EDIT:
Found the problem with memcpy. Turns out it had a third argument.


Last edited by Kenchu; 03/07/08 18:12.