I usually look at this in terms of ownership. For example, you can say that obj1 owns the array whose first character is pointed to by obj1.x1. So, when you are done with obj1, you will free(obj1.x1).
Now, when you make obj2 a copy of obj1, does obj2 own a copy of that array, or does it merely refer to that array? If it merely refers to that array then obj2 = obj1; is good enough, but you must be careful when you use free(). But if obj2 owns a copy of that array, then you would malloc() space for that copy, then copy over the elements, e.g., with memcpy().
Originally Posted by
stavos77
Why does memcpy fail?
What exactly did you try? I found sganesh's example to be rather unclear. You need to memcpy() with respect to the x1 members, not with respect to the struct myStruct objects, otherwise you do not get the "deep copy" that you probably want.
For example:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct myStruct
{
int *x1;
int x2;
} myStruct;
void myStruct_init(myStruct *obj);
myStruct *myStruct_copy(myStruct *dest, const myStruct *source);
void myStruct_print(FILE *fp, const myStruct *obj);
int main(void)
{
struct myStruct obj1 = {0, 2};
struct myStruct obj2;
/* Let's allocate space for x2 number of elements */
obj1.x1 = malloc(obj1.x2 * sizeof(obj1.x1[0]));
/* assume that malloc does not return a null pointer */
myStruct_init(&obj1);
myStruct_print(stdout, &obj1);
myStruct_copy(&obj2, &obj1);
myStruct_print(stdout, &obj2);
free(obj1.x1);
free(obj2.x1);
return 0;
}
void myStruct_init(myStruct *obj)
{
int i;
for (i = 0; i < obj->x2; ++i)
{
obj->x1[i] = i;
}
}
myStruct *myStruct_copy(myStruct *dest, const myStruct *source)
{
int *temp = malloc(source->x2 * sizeof(source->x1[0]));
if (temp)
{
dest->x2 = source->x2;
dest->x1 = temp;
memcpy(dest->x1, source->x1, source->x2 * sizeof(source->x1[0]));
return dest;
}
else
{
return 0;
}
}
void myStruct_print(FILE *fp, const myStruct *obj)
{
fprintf(fp, "%d: ", obj->x2);
if (obj->x1)
{
int i;
for (i = 0; i < obj->x2; ++i)
{
fprintf(fp, "%d ", obj->x1[i]);
}
}
fprintf(fp, "\n");
}