I'm trying to expand a dynamic array of objects of a class called Coffee( Coffee * brands = new Coffee[sizeOf];
), usually I would just make a temp dynamic array whose size is one bigger than the initial array's size - I copy them over to temp, add the new one at the end, delete the old one, make it anew but expanded, and copy back everything to it from temp.
But now, I have to do it outside of the main function where the array must be situated(yes, this is an assignment, a tricky one at that), so I carry in the array and the size through as parameters, and start off making the temp array and copying over everything, adding the new object at the end.
Now this is where I'm lost; if I want to delete the array from main through the subfunction, how do I replace it/make it anew through the same function? It sounds nonsensical to me, but I don't see how to get that extra notch in required, or is it just about adding +1 to the size variable and copying over the new object's info to the last slot somehow?
This question isn't a duplicate because I've checked some other answers to other questions but can't find this same one, because this is about making the change happen from another function specifically with a dynamic array, every answer I've seen(such as this one: How to expand an array dynamically in C++? {like in vector } ) deals with either the main-function only, or vectors are suggested(which doesn't help me since I have to use dynamic arrays), and I get confused by some unrelated minutiae like *(p+i) = i
.
Also, can somebody explain the scope differences here and why your solution works in harmony with them? What is it I've neglected or missed?
Some code:
#include <iostream>
#include <string>
#include "Coffee.h"
using namespace std;
void addCoffee(Coffee c[], int &amount);
void showAllCoffees(Coffee c[], int amount);
int main()
{
int sizeOf = 5;
Coffee * brand = new Coffee[sizeOf];
addCoffee(brand, &sizeOf);
showAllCoffees(brand, sizeOf); //nevermind this part,
//just added it so it makes more sense
delete [] brand;
return 0;
}
void addCoffee(Coffee c[], int &amount){
string name;
amount++;
Coffee * temp = new Coffee[amount];
for(int i=0;i<amount-1;i++){
temp[i] = c[i];
}
cout<<"What is the coffee's name?: ";
cin>>name;
temp[amount-1].setName(name);
/*THIS IS WHERE I'M NOT SURE WHAT TO DO*/
delete [] temp;
}