addFriend() is leaking memory like crazy. You're storing objects of person in your list, so you're going to make a copy anyway, there's no point faffing about with pointers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
person addFriend ()
{
person temp;
cout << "\nPlease enter the name of your friend: ";
cin >> temp.name;
cout << "Please enter last date spoken to: ";
cin >> temp.number;
return temp;
}
...
int main()
{
...
if (1 == answer)
{
list[i++] = addFriend();
}
|
Things would be different if list was a collection of pointers.
The growArray() is another problem, the parameter is an array of pointers, but of course what we have and pass is an array of objects. We also pass size, an int where a pointer is required.
By doubling size before the loop we'll end up trying to copy twice as much data as we have, thereby accessing out of bounds data.
With these changes it should at least compile and run, and watch out for istream errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
#include <string>
using namespace std;
struct person
{
string name;
int number;
};
person *growArray (person *values, int *size)
{
person *temp = new person[2 * (*size)];
for (int i = 0; i < *size; i++)
{
temp[i].name = values[i].name; // here is where i have problems
temp[i].number = values[i].number;
}
(*size) *= 2;
delete [] values;
return (temp);
}
person addFriend ()
{
person temp;
cout << "\nPlease enter the name of your friend: ";
cin >> temp.name;
cout << "Please enter last date spoken to: ";
cin >> temp.number;
return temp;
}
//int updateValue (int *array[], int index)
int main()
{
int size = 2;
person *list = new person[size];
cout << "Welcome to Person Manager 2014, the game where you pretend to have friends and die!!!\n\n";
for (int i = 0; i < size;)
{
if ((i + 1) >= size)
{
list = growArray (list, &size);
}
int answer;
cout << "What would you like to do?\n1)Input new friends\n2)Update last time talked\n3)Sort by name\n4)Sort by name\n";
cout << "\nOption number: ";
cin >> answer;
if (answer == 1)
{
list[i++] = addFriend ();
}
else if (answer == 2)
{
//string answer2; (part of the code is comented out to test things)
//list[i].number = updateNumber;
}
else if (answer == 3)
{
// displayNumber (list);
}
else if (answer == 4)
{
//displayName (list);
}
else if (answer > 4 || answer < 0)
{
cout << "Invalid number, choose again\n\n";
}
}
}
|
In main, because the loop termination is " i < size" ( I changed that from "i < size + 1") and size doubles when i == size + 1, size is a moving target i can never approach. Whenever a user selects an option, they will enter an infinite loop. You need to make one of the options a choice to break out of the loop.