Copying from One Dynamically Allocated Array to Another C++

前端 未结 3 2065
北海茫月
北海茫月 2021-02-09 07:26

This seems like it should have a super easy solution, but I just can\'t figure it out. I am simply creating a resized array and trying to copy all the original values over, and

相关标签:
3条回答
  • 2021-02-09 07:53

    orig must be a pointer to a pointer to assign it to resized:

    int **orig;
    *orig = resized;
    
    0 讨论(0)
  • 2021-02-09 07:56

    I highly suggest replacing the arrays with std::vector<int>. This data structure will resize as needed and the resizing has already been tested.

    0 讨论(0)
  • 2021-02-09 07:59

    Remember, parameters in C++ are passed by value. You are assigning resized to a copy of the pointer that was passed to you, the pointer outside the function remains the same.

    You should either use a double indirection (or a "double pointer", i.e. a pointer to a pointer to int):

    void ResizeArray(int **orig, int size) {
        int *resized = new int[size * 2]; 
        for (int i = 0; i < size; i ++)
            resized[i] = (*orig)[i];
        delete [] *orig;
        *orig = resized;
    }
    

    or a reference to the pointer:

    void ResizeArray(int *&orig, int size) {
        int *resized = new int[size * 2]; 
        for (int i = 0; i < size; i ++)
            resized[i] = orig[i];
        delete [] orig;
        orig = resized;
    }
    

    By the way, for array sizes you should use the type std::size_t from <cstddef> - it is guaranteed to hold the size for any object and makes clear that we are dealing with the size of an object.

    0 讨论(0)
提交回复
热议问题