Reputation: 95
I am trying to put the strings in a temporary array into a dynamic array. But the compiler just breaks when it hits that.
where dynaicArray is called:
string* dynamicArray = NULL;
Here is where it is breaking:
for (int i = 1; i <= (size); i++)
{
dynamicArray[i] = tempArray[i];
}
Where tempArray is filled:
void populateArray(int& size, string*& dynamicArray)
{
char decide;
string tempArray[100]; //Holds the strings until the size is known
bool moreStrings = true;
while (moreStrings == true)
{
cout << "\nEnter your string here:";
cin >> tempArray[size];
cout << "\nDo you want to enter another string? Y/N:";
cin >> decide;
decide = toupper(decide);
size ++;
dynamicArray = new string[size];
if (decide == 'N')
{
for (int i = 1; i <= (size); i++) //moves all of the strings from tempArray to dynamicArray
{
string temp;
temp = tempArray[i];
dynamicArray[i] = temp;
}
moreStrings = false;
}
}
}
PS: I know vectors are better. Unfortunately they're not an option.
Upvotes: 1
Views: 121
Reputation: 1607
Some design ideas:
if (decide == 'N')
block is better placed after the while, to make the while smaller == more readablemoreStrings
var directly with the result of your decide == 'N'
; no need for an explicit if
there anymoredynamicArray = new string[size];
in each pass through the while, which is an enormous memory leak (you'r overwriting the newly created dynamic array with a new copy without reclaiming the old one out first - see dalete[])size
in the function before you use it - much safer; callers don't need to remember to do it themselvesfor (int i = 1; i <= (size); i++)
: the () around size are superfluous++size
and ++i
in these contexts; it's a bit more efficienttmp
to copy from the temp array to the dynamic one and the code is also somewhat structured to suggest you're using it to swap the strings between the two arrays (you're not) - rename the tmp variable or get rid of it altogetherUpvotes: 1