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. 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
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.
CodePudding user response:
There are two problems with the modifyArray
function.
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
).
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;
}