Thread: Copying structures containing pointers

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    13

    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

  2. #2
    Registered User
    Join Date
    Feb 2010
    Posts
    57

    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.

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    36

    Copying structures

    You can simply assign one object to another.You try the following code.

    Code:
    #include	<stdio.h>
    #include	<stdlib.h>
    struct myStruct
    {
    	int *x1;
    	int x2;
    };
    
    int main()
    {
    	struct myStruct obj1;
    	struct myStruct obj2;
    
    	obj1.x1 = malloc(5*sizeof(int));
    	*obj1.x1 =40;
    	obj1.x2 =20;
    	obj2=obj1;
    	printf ( "Obj1 Values\nx1:%d and x2:%d\n",*obj1.x1,obj1.x2  );
    	printf ( "Obj2 Values\nx1:%d and x2:%d\n",*obj2.x1,obj2.x2  );
    }

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can copy structure values with the assignment operator, but that does not duplicate what is pointed at.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    13
    I tried both ways.

    By using the assignment operator, I got the same values (however I am a bit confused by the last post of quzah)

    Obj1 Values
    x1:40 and x2:20
    Obj2 Values
    x1:40 and x2:20

    When using memcpy, I got an error result

    Obj1 Values
    x1:40 and x2:20
    Obj2 Values
    x1:3998248 and x2:20

    So, when using assignment operator, I get the result I want, but do I have the same memory allocated?

    Why does memcpy fail?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    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().

    Quote 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");
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    13

    Smile

    Thanks laserlight,

    I will have to study your answer a bit since I do not have too much experience with C

  8. #8
    Registered User
    Join Date
    Feb 2010
    Posts
    57

    Re: Copying structures containing pointers

    Quote Originally Posted by quzah View Post
    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.

  9. #9
    Registered User
    Join Date
    Mar 2010
    Posts
    13
    I guess that if I use the memcpy function, I will get a copy of the structure pointer only and not the whole allocated area via this pointer.

    I mean that after a copy, both structures will have a pointer as a member that will point to the same memory area, right?

    And If I need to have the memory area replicated as well, then I should use a function.

    This is what I have understood so far!!

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by stavos77
    I guess that if I use the memcpy function, I will get a copy of the structure pointer only and not the whole allocated area via this pointer.
    Yes, if you use memcpy on the objects. As you can see, I used it to copy the array.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Mar 2010
    Posts
    13
    I think I got it now.

    Thank you

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with 2d array of structures and pointers.
    By CopperHead4750 in forum C Programming
    Replies: 2
    Last Post: 12-09-2009, 03:02 PM
  2. Arrays of pointers inside structures.
    By Posto2012 in forum C Programming
    Replies: 7
    Last Post: 11-18-2009, 12:58 AM
  3. Generic Pointers to structures
    By dunxton in forum C Programming
    Replies: 8
    Last Post: 02-20-2009, 10:23 AM
  4. returning pointers to structures
    By Giant in forum C++ Programming
    Replies: 2
    Last Post: 06-20-2005, 08:40 AM
  5. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 09:04 AM