简体   繁体   English

使用函数修改动态数组会在第二次调用该函数时修改原始数组

[英]modifying a dynamic array using a function modifies the original array the second time calling the function

This is a sample code of a bigger program.这是一个更大程序的示例代码。 The modifyArray function increases the array size by one then adds a new string element which here is "eeee", calling the function once works fine but when calling it the second time it modifies the original array, i want it to modify the array that came out the first modifyArray function. modifyArray函数将数组大小增加一个,然后添加一个新的字符串元素,这里是“eeee”,调用该函数一次工作正常但是当第二次调用它时它修改了原始数组,我希望它修改来的数组出第一个modifyArray函数。 here is the code这是代码

#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
#include <filesystem>
#include <iomanip>
#include <string.h>
#include <sstream>

using namespace std;

void modifyArray(string*&, int);

int main()
{
    int arraySize = 4;
    string* playlist;
    playlist = new string[arraySize];
    playlist[0] = "aaaa";
    playlist[1] = "bbbb";
    playlist[2] = "cccc";
    playlist[3] = "dddd";
    
    modifyArray(playlist, arraySize);
        modifyArray(playlist, arraySize);
    for (int i = 0; i < arraySize; i++)
    {
        cout << playlist[i] << endl;
    }
}

void modifyArray(string*& Fplaylist, int FarraySize)
{
    string* subPlaylist;
    subPlaylist = new string[FarraySize];
    copy(Fplaylist, Fplaylist + FarraySize, subPlaylist);

    delete[]Fplaylist;
    FarraySize = FarraySize + 1;
    Fplaylist = new string[FarraySize];
    copy(subPlaylist, subPlaylist + FarraySize - 1, Fplaylist);
    Fplaylist[FarraySize - 1] = "eeee";
    

}

expected output:预期输出:

aaaa
bbbb
cccc
dddd
eeee
eeee

Real output:实际输出:

aaaa
bbbb
cccc
dddd

ps: I can't use vectors ps:我不能使用矢量

I tried other things like storing the array in an external text file but I get the same results.我尝试了其他方法,例如将数组存储在外部文本文件中,但得到的结果相同。 I am a beginner at C++ so I really don't understand pointers quite well.我是 C++ 的初学者,所以我真的不太了解指针。

There are two problems with the modifyArray function. modifyArray函数有两个问题。

The first problem is that FarraySize should be a reference so that changes to it affect the variable used to call the function (exactly like Fplaylist ).第一个问题是FarraySize应该是一个引用,以便对它的更改会影响用于调用函数的变量(与Fplaylist完全一样)。

The second problem is that the function makes two allocations and two copies, when it should be one of each.第二个问题是该函数进行了两次分配和两次复制,而它应该是每一次分配和两次复制。 Making two allocations leaks memory, and make two copies is needlessly inefficient.进行两次分配会泄漏内存,并且进行两次复制是不必要的低效。

Here's a version that works这是一个有效的版本

void modifyArray(string*& Fplaylist, int& FarraySize)
{
    string* newPlaylist = new string[FarraySize + 1];
    copy(Fplaylist, Fplaylist + FarraySize, newPlaylist);
    newPlaylist[FarraySize++] = "eeee";
    delete[] Fplaylist;
    Fplaylist = newPlaylist;
}

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

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