Hello! I know I have been posting a lot but I have been learning so much from this community! So thank you. Someone has mentioned that it would more organized for me to use struct instead of writing two arrays. I agree, however, I am not quite sure how the syntax will work out. For example,
int *p_talk = new int[size];
string *p_name = new string[size];
How would I write this using structures? So this is what I did,
1 2 3 4 5 6 7 8 9 10 11 12 13 14
struct info
{
int *p_talk;
string *p_name;
};
int main ()
{
int size = 10;
person.p_talk = newint[size];
person.p_name = new string[size];
return 0;
}
However, this is writing two arrays again. Instead of using structures to organize my arrays better. Any suggestions?
softrix has posted a very nice example that is very close to what you are doing.
As his linked post indicated, it uses std::vector. Not clear if you've learned that yet.
To add some further explanation:
Your info struct should contain information about one and only one contact. You support multiple contacts by having an array (or vector) of contact instances.
1 2 3 4
struct info // Represents one contact
{ int days_ago; // changed the name to make it clearer
string name; // No need for this to be a pointer.
};
Now, you can represent multiple contacts in one of several ways.
1 2 3 4 5 6 7 8 9
// 1. A simple array
info contacts[MAX_CONTACTS];
// 2. A vector of contacts (recommended)
std::vector<info> contacts;
// 3. A dynamically allocated array
info * p_contacts;
p_contacts = new info[MAX_CONTACTS];
...
delete [] p_contacts; // Be sure to delete
BTW: You have a memory leak in your original program. p_talk and p_name are never deleted. You should always have a delete for every new.