Copying structures containing pointers
Hi everyone. I am a new member. I am relatively new to C and I would like to ask you how to copy two structures that contain pointers as members. For example, I have this code fragment
Code:
struct myStruct
{
int *x1;
int x2;
};
void main()
struct myStruct obj1;
struct myStruct obj2;
obj1.x1 = malloc(5*sizeof(int));
*obj1.x1 =40;
obj1.x2 =20;
How can I make a copy of obj1 to obj2 ?
Thanks
Re: Copying structures containing pointers
Normally, we can copy the structures in a two way.
* Assigning structure using assignment operator
Code:
obj2=obj1;
obj2.x1 = malloc(5*sizeof(int));
* And you can copy the structure using memcpy.
Code:
memcpy((struct myStruct*)&obj2,(struct myStruct *)&obj1,sizeof(struct myStruct));
obj2.x1 = malloc(5*sizeof(int));
And if you want the new memory for the pointer member (int *x1) of that structure you need to allocate the memory.
Re: Copying structures containing pointers
Quote:
Originally Posted by
quzah
You can copy structure values with the assignment operator, but that does not duplicate what is pointed at.
Quzah.
Code:
obj2=obj1;
(*obj2.x1)++;
printf("obj2 %d mem(%d):%d\n",*obj2.x1,obj2.x1,obj2.x2);
printf("obj1 %d mem(%d):%d\n",*obj1.x1,obj1.x1,obj1.x2);
It gives output as ,
obj2 41 mem(163155976):20
obj1 41 mem(163155976):20
It gives duplicate only normally. But if you want to new memory you need to allocate the new memory.