简体   繁体   English

在C ++中复制数组的麻烦

[英]a trouble of copying array in C++

I am copying an array in C++, here is the code: 我正在用C ++复制一个数组,下面是代码:

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? 怎么了

The array is copied properly, though, by incrementing dest you are losing the actual beginning. 但是,通过增加dest可以正确复制该数组,从而使您失去了实际的开始。

You need to keep a copy of dest to loop after it. 您需要保留一份dest副本以在其后循环。 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. 最后,在C ++中,您可能希望使用std::vector而不是使用数组,而这些数组以透明的方式完成所有这些工作,同时又使性能达到最低限度。

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;

The starting pointer is not saved with int *dest = new int[sz]; 起始指针不保存为int *dest = new int[sz]; , after *dest++ in the while loop, so the output is out of range of the array. 在while循环中的*dest++之后,因此输出超出数组范围。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM