I need to directly copy a value from array
to array2
which is a pointer array to use pointing organ
values. And in this code, i have used memcpy
function but it didn't work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct organ{
char *name;
};
struct human{
struct organ *org;
};
void main(void){
struct human*array = malloc(sizeof(struct human));
array[0].org = malloc(sizeof(struct organ));
array[0].org[0].name= malloc(6);
struct human*array2 = malloc(sizeof(struct human));
array2[0].org = malloc(sizeof(struct organ));
strcpy(array[0].org[0].name, "lungs");
printf("array name: %s\n",array[0].org[0].name);
memcpy(&array2[0].org[0], &array[0].org[0], sizeof(struct organ));
free(array[0].org[0].name);
free(array[0].org);
free(array);
printf("array2 name: %s\n",(array2[0].org[0].name));
free(array2[0].org);
free(array2);
}
What did i made wrong? How can i fix this problem ?
Here is a simplification of the problem as in your code:
struct organ a, b;
a.name = malloc(6);
strcpy(a.name, "hello");
b = a;
free(a.name);
puts(b.name);
Your code uses memcpy
, but memcpy(&b, &a, sizeof b);
is practically the same as b = a;
so I have used the simpler syntax in my example.
The problem is that there is only one call to malloc
. Both a.name
and b.name
point to the same memory block. You free that block and then try to output its contents.
Perhaps what you want to do is to make b.name
have its own memory block. This means you need to call malloc
again, the =
operator (or the memcpy
function) does not call malloc.
For example in my code, change the b = a;
line to:
b.name = malloc( strlen(a.name) + 1 );
strcpy(b.name, a.name);
In other words, the procedure for a so-called "deep copy" of a struct organ
is not the same as the procedure performed by the assignment operator.
I would recommend that you make a function for performing a copy of struct organ
that behaves in the way you want; and call that function instead of using the assignment operator or memcpy
.
You could also do the same for copying of a struct human
.