Reputation: 138
I am copying an array in C++, here is the code:
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *source = arr1;
size_t sz = sizeof(arr1) / sizeof(*arr1); // number of elements
int *dest = new int[sz]; // uninitialized elements
while (source != arr1 + sz)
*dest++ = *source++; // copy element and increment pointers
int *p = dest;
while (p != dest + sz) {
cout << *p++ << endl;
}
after running the code above-mentioned, I got:
714124054
51734
9647968
9639960
0
0
0
0
0
0
what's the trouble?
Upvotes: 1
Views: 104
Reputation: 7225
The starting pointer is not saved with int *dest = new int[sz];
, after *dest++
in the while loop, so the output is out of range of the array.
The revised code:
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *source = arr1;
size_t sz = sizeof(arr1) / sizeof(*arr1); // number of elements
int *dest = new int[sz]; // uninitialized elements
int *temp_dest = dest;
while (source != arr1 + sz)
*temp_dest++ = *source++; // copy element and increment pointers
int *p = dest;
while (p != dest + sz) {
cout << *p++ << endl;
}
Upvotes: 0
Reputation: 8421
The array is copied properly, though, by incrementing dest
you are losing the actual beginning.
You need to keep a copy of dest
to loop after it. Also don't forget to free the memory after you have allocated it.
Finally, in C++ you'll probably want to use std::vector
instead of arrays that does all this in a transparent way while trading a minimum amount of performance.
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *source = arr1;
size_t sz = sizeof(arr1) / sizeof(*arr1); // number of elements
int *dest = new int[sz]; // uninitialized elements
int *d = dest;
while (source != arr1 + sz)
*d++ = *source++; // copy element and increment pointers
int *p = dest;
while (p != dest + sz) {
cout << *p++ << endl;
}
[...]
delete[] dest;
Upvotes: 5