程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将静态数组复制到动态数组 C++大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决将静态数组复制到动态数组 C++?

开发过程中遇到将静态数组复制到动态数组 C++的问题如何解决?下面主要结合日常开发的经验,给出你关于将静态数组复制到动态数组 C++的解决方法建议,希望对你解决将静态数组复制到动态数组 C++有所启发或帮助;

所以当我注意到这一点时,我正在玩一些 C++ 的基础知识:

int * ptr = new int[3],arr[3] = { 11,13,15 };
    for (int i = 0; i < 3; i++)
        ptr[i] = arr[i];

cout << ptr[0] << ' ' << ptr[1] << ' ' << ptr[2] << endl;

这段代码将完美地插入并打印出值:11 13 15。

而当我这样写时:

int size=0,* ptr = new int[size],15 };
for (int i = 0; i < 3; i++)
{
    ptr = new int[++size];
    ptr[i] = arr[i];
}
cout << ptr[0] << ' ' << ptr[1] << ' ' << ptr[2] << endl;

当我一次增加一个值时,它会打印出来:

-842150451 -842150451 15

为什么当我在开始时定义总大小时,值被正确插入,但是当我一次增加一步时却没有?另外,有什么方法可以编写第二个代码,但要以一种可行的方式吗?

解决方法

正如@Ch3esteR 在评论中指出的那样。问题是你正在重新分配你的 每次迭代中的数组,从而归零(或者在您的情况下,捕获一些随机 堆上的值)。

我想说更大的解决方案可能是使用标准容器来处理内存。 Here is a solution 用于修复您的原始代码 original() 以及如何使用 std::vector 处理动态数组的建议替代方案。

#include <vector>
#include <iostream>

using namespace std;

void original() {
    const int arr[3] = { 11,13,15 };

    const int size=3;
    auto ptr = new int[size]; // this is what you want to do
    std::copy(arr,arr + size,ptr); // Standard function for copying

    cout << ptr[0] << ' ' << ptr[1] << ' ' << ptr[2] << endl;
}

int main() {
    original();

    const int arr[3] = { 11,15 }; // You might want to make this a std::vector too

    std::vector<int> result{arr,arr + 3};

    // std::vector<int> result;  // Or if the question was how to do it dynamically
    // for (auto i: arr)
    // {
    //     result.push_BACk(i); // Dynamic add
    // }

    cout << result[0] << ' ' << result[1] << ' ' << result[2] << endl;
}


应要求:如何用指针来做(不要这样做,除非你有一些外部约束迫使你这样做,就像老师一样)

#include <iostream>

using namespace std;

// Reallocate memory and delete the old pointer
int *resize(int *arr,size_t oldSize,size_t newSizE) {
    auto newArr = new int[newSize];

    auto copySize = std::min(oldSize,newSizE); // Handle both growing and shrinking resize
    std::copy(arr,arr + copySize,newArr); // Copy your old data
    // Or do it like this
    // for (size_t i = 0; i < copySize,++i) {
    //    newArraY[i] = arr[i]
    // }

    delete [] arr;

    return newArr;

}

int main() {
    auto arr = new int[2] { 11,13 }; // Observe 'new' here
    size_t size = 3;

    // "resize" the array arr (in practice you are just creaTing a new onE)
    arr = resize(arr,size,size + 1);

    // Assign your new value
    arr[2] = 14;


    cout << arr[0] << ' ' << arr[1] << ' ' << arr[2] << endl;

    delete [] arr; // Remember,try to not manual memory management,// only use it in class when you are learning the basics,otherwise use
                   // std::unique_ptr or std::shared_ptr
}

大佬总结

以上是大佬教程为你收集整理的将静态数组复制到动态数组 C++全部内容,希望文章能够帮你解决将静态数组复制到动态数组 C++所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。