I want to copy some data stored in a struct to an other. Does the code below work?? Is it recommended or not?
#define SIZE 100
struct {
int *a;
int *b;
} Test;
Test t1;
t1.a = malloc(SIZE);
t1.b = malloc(SIZE);
Test t2;
memcpy(t2,t1,sizeof(Test));
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Whether it works depends on what you intend it to do. It copies the bits from
t1tot2, including padding, but of course it copies the pointers, not the pointed-to values.If you don’t care about the padding bits – and why should you – a simple assignment
is all you need to copy the pointers.
If you want the pointed-to values duplicated and copied, neither your code nor simple assignment works.
To copy the pointed-to memory blocks, first of all, you must know their size. There is no (portable) way to find out the size of the pointed-to memory block from the pointer.
If the size is given by a
#define, you can of course reuse that, otherwise you need to store the sizes of the allocated blocks somewhere.But since the newly allocated memory blocks have different addresses than the blocks to be copied, we need not copy the pointer vlaues from
t1tot2at all.