patterncppMinor
Copying one array to the end of another array
Viewed 0 times
thearrayonecopyinganotherend
Problem
I wrote a program that places values in one array to the end of another array. It keeps the order of the values. If the second array is bigger, then there will be leading zeroes.
Is there anything I can improve? How do I simplify this program?
Is there anything I can improve? How do I simplify this program?
#include
int main()
{
int fromArray[10] = {11,22,33,44,55,66,77,88,99,100};
int toArray[15] = {};
int size = sizeof(fromArray)/sizeof(fromArray[0]);
int * first = fromArray;
int * last = first + size; //One past end of array
int * toLast = toArray + sizeof(toArray)/sizeof(toArray[0]); //One past end of array
for(first; first != last;)
*(--toLast) = *(--last);
for(int i=0; i<sizeof(toArray)/sizeof(toArray[0]); i++)
std::cout << toArray[i] << " ";
}Solution
Be aware that
sizeof is actually an operator, not a function. It also returns std::size_t, which is an unsigned integer type. You currently have size as an int, which is a signed type. If you had your compiler warnings up high (and they should be), then you probably would've been warned about this.std::size_t size = sizeof(fromArray)/sizeof(fromArray[0]);Code Snippets
std::size_t size = sizeof(fromArray)/sizeof(fromArray[0]);Context
StackExchange Code Review Q#66444, answer score: 6
Revisions (0)
No revisions yet.