Thread: Copying Arrays

  1. #1
    Registered User
    Join Date
    Dec 2002

    Copying Arrays

    What is the correct way to copy an array to another array in C++? Currently, I am just saying: array1=array2;

    I have a feeling there is a problem with this, because there are some compilers which are complaining and some which aren't. Is the correct way just to run a for loop and copy each value one by one?

    Thanks, appreciate it.

  2. #2
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    That seems a sensible way of copying arrays to me. As long as you stay within the bounds of the arrays, there shouldn't be any problems.
    Be a leader and not a follower.

  3. #3
    Registered User abrege's Avatar
    Join Date
    Nov 2002
    This is logical for me...why wouldn't it be correct?

    for(int i = 0; i < arraysize; i ++)
         array2[i] = array1[i];
    I am against the teaching of evolution in schools. I am also against widespread
    literacy and the refrigeration of food.

  4. #4
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    You could use memcpy, i.e.

    void *memcpy(void *dest, const void *src, size_t n);

    Where n is the number of bytes to be copied.

  5. #5
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    You can encapsulate it in a class or struct or union and just let the assignment operator do it for you.


    struct Array
        int Data[5];
    // Then you can do:
    Array A, B;
    /* ... */
    A = B;
    However, I wouldn't recommend doing this in most places unless it makes logical sense that the array should be encapsulated.

  6. #6
    I lurk
    Join Date
    Aug 2002
    Or, you could *gasp* use a vector.
    #include <vector>
    // ...
    std::vector<int> intvec1;
    // ...
    std::vector<int> intvec2(intvec1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying 2-d arrays
    By Holtzy in forum C++ Programming
    Replies: 11
    Last Post: 03-14-2008, 03:44 PM
  2. Is this poor coding? copying arrays of doubles
    By Hansie in forum C Programming
    Replies: 12
    Last Post: 05-25-2007, 02:34 PM
  3. copying strings to heap character arrays
    By SkyRaign in forum C++ Programming
    Replies: 4
    Last Post: 11-26-2006, 01:08 PM
  4. Copying array's
    By big146 in forum C++ Programming
    Replies: 4
    Last Post: 06-15-2004, 01:25 PM
  5. copying character arrays
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 04-20-2002, 05:39 PM