0

I've got Function1 where user inputs data in array1. I must make array2 in Function2 to be equal to array1 from Function1.

How do I "tell it" that it should use array1 from Function1?

I've tried

array2[50] = array1[50];

but of course that is not working.

5
  • I would suggest this -> devx.com/tips/Tip/13291 Commented May 7, 2012 at 9:32
  • What is your goal ? Do you only need the values of array1 to be read by Function2 ? do you need to modify them ? Did you consider using something like a vector instead of an array ? Commented May 7, 2012 at 10:58
  • 1
    Do you really ned to copy the array? Why not just use the same array? Commented May 7, 2012 at 10:58
  • I needed to copy the array and modify the copy. I have yet to study how vectors work, so I have no idea how to use them. Thanks though. Commented May 7, 2012 at 11:56
  • Vectors work like "smart arrays". Besides automatic resizing and bounds checking, you can simply do vector2=vector1 and vector2 will be an independant copy of vector 1 Commented May 8, 2012 at 20:09

3 Answers 3

2

You need to copy array1 elementwise into array2, e.g.

for (unsigned i=0; i<array1_size; ++i) {
    array2[i] = array1[i];
}

You can also use std::copy from the algorithm header.

std::copy(array1, array1 + array1_size, array2);

For both approaches you need to know the number of elements in array1 (array1_size in the examples). Also, array2 needs to be at least as big as array1.

Sign up to request clarification or add additional context in comments.

Comments

0

Iterate over all elements in one array and assign them to the second one.

Comments

-1

memcpy(second_array, first_array, sizeof(second_array));

[Original Source Site][http://www.devx.com/tips/Tip/13291]

4 Comments

Depending on what his arrays contain this can be problematic since it doesn't invoke copy constructors but copies raw memory.
Well there is no indicator in the question that shows that there are pointers to structures or objects, in addition there is no hint that a shallow or deep copy is needed, if he only has int's or chars in the table the application will me enormously fast compared to std::copy, i claim that more than 90% of all realtime systems use those low level mechanisms to copy arrays and even single objects
Did you benchmark this? With my compiler and int arrays std::copy is as fast as memcpy but much safer.
This can depend on your platform/compiler , std::copy uses memmove which is not as fast as memcpy because it containts extra checks, i have no system here to properly make performance tests, if you make 1000 memcpy's vs 1000 memoves you will already see the difference, adding the std::copy's check will decrease performance again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.