another dynamic memory allocation problem
the question is;
Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value (but don't let them put in bogus numbers like negative values). Make it possible to display the list sorted by the names of the friends of by how recently it was since they talked to each friend.
Below is what I have done. The problem I am having is that the array will not grow in size. (Another problem which I have not tackled yet is how to remember if the same user updates their noDays figure, but will give that a go after the array grows);
Code:
#include <iostream>
#include <string>
using namespace std;
int *growArray (int * friends, int * size)
{
*size *= 2;
int *new_friends = new int[*size];
for (int i=0; i < *size; i++) {
new_friends[i] = friends[i];
}
delete [] friends;
return new_friends;
}
string *growArray2 (string * name1, int * size)
{
*size *= 2;
string *new_name2 = new string[*size];
for (int i=0; i < *size; i++) {
new_name2[i] = name1[i];
}
delete [] name1;
return new_name2;
}
void printArray (string *name1, int *friends,int size, int element_set)
{
cout << "the total size of the array is: " << size << endl;
cout << "Values in the array: " << endl;
for (int i = 0; i < element_set; ++i)
{
cout << name1[i] << "[" << i << "] = " << friends[i] << " days since you last spoke to them" << endl;
}
}
int main()
{
string exit = "X";
string name;
int noDays;
int next_element = 0;
int size = 4;
int *friends = new int[size];
string *name1 = new string [size];
cout << "Please enter your friends name" << endl;
cin >> name;
cout << "Please enter no of days you last spoke to them" << endl;
cin >> noDays;
while(true) {
if (size == next_element+1) {
friends = growArray(friends, &size);
name1 = growArray2(name1, &size);
}
friends[next_element] = noDays;
name1[next_element] = name;
next_element++;
printArray(name1, friends, size , next_element);
cout << "Please enter your friends name or X to exit" << endl;
cin >> name;
if (name == exit) {
break;
}
cout << "Please enter no of days you last spoke to them" << endl;
cin >> noDays;
}
delete name1;
return 0;
}