Copy dynamically allocated array of ints

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dperren
    New Member
    • Mar 2007
    • 10

    Copy dynamically allocated array of ints

    Example code:

    Code:
    		int a, b, c;
    
    		int *t1;
    		int *t2;
    		t1 = malloc(3*sizeof(int));
    		t1[0] = 1;
    		t1[1] = 2;
    		t1[2] = 3;
    		t2 = malloc(3*sizeof(int));
    		t2 = t1;
    		
    		a = t2[0];
    		b = t2[1];
    		c = t2[2];
    
    		t2[0] = 5;
    This appears to work fine (copying t1 into t2), until modifying t2, when t1 is modified as well since you have obviously only copied the pointer, rather than the data value.

    I then pieced together a 'copy' method:
    Code:
    void copy(int *to, int *from)
    {
    	int c;
    	for(c=0; c<sizeof(from)/sizeof(int); c++)
    	{
    		to[c] = from[c];
    	}
    }
    to replace 't2 = t1' with 'copy(t2, t1)', but this doesn't seem to work either. I think I'm just generally a bit confused, so can anyone poke my copy method in the correct direction?

    Thanks,
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You need to pass in a double pointer for to, that is an int**, since you're modifying a copy of the pointer otherwise. Also, from should be a const parameter, since it's not being changed.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      The problem is, when you pass in an array to a function, all that shows up is a pointer. It's no longer an array, and thus, using your sizeof division will not give you the size of the array - it will give you the size of an integer pointer (probably 4 bytes) divided by the size of an integer (probably 4 bytes).

      In order to know the size, you have to pass in an additional int value indicating the size. You would them copy elements from[0], from[1],..., from[size-1] to to[0], to[1],..., to[size-1], respectively.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        You may wish to consider using the standard library function memcpy

        Comment

        • dperren
          New Member
          • Mar 2007
          • 10

          #5
          Ahh, brilliant!

          Combination of memcpy and remembering the amount of memory initially allocated did the trick.

          Thanks everyone!

          Comment

          Working...