I am trying to pass arbitrary array of structs to a function. It compiles well but it prints nothing.
Here is the arbitrary array of structs: aFriend *p_array=new aFriend[index];
The function call updateTalk(p_array, index); and the function void updateTalk(aFriend an_array[], int a_size)
Also here is the whole code:
#include <iostream>
using namespace std;
struct aFriend
{
string name;
int days_ago=0;
};
aFriend addFriend(int& index)
{
aFriend newFriend;
cout<<"Enter friend's name:\t";
cin>>newFriend.name;
do{
cout<<"How many days ago you talked with him/her:\t";
cin>>newFriend.days_ago;
} while (newFriend.days_ago<=0);
index++;
return newFriend;
}
void updateTalk(aFriend an_array[], int a_size)
{
cout<<"an_array[0].name="<<an_array[0].name<<endl;
cout<<"Select one of the following names:\n";
for(int i=0;i<a_size;i++)
{
cout<<"1. "<<an_array[i].name;
}
cout<<endl;
}
void printList()
{
}
int index=0;
int main()
{
cout<<"1. Add friend\n2. Update last talk\n3. Print list\n4. Exit\n";
int pick;
cin>>pick;
aFriend *p_array=new aFriend[index];
switch (pick)
{
case 1: addFriend(index);return main();
case 2: updateTalk(p_array, index); return main();
case 3: printList(); return main();
case 4: return 0;
default: cout<<"Error! Please select one of the available options!\n"; return main();
}
}
indexis0at the start, sop_arraywill be empty. Usestd::vectorinstead.p_arrayto contain enough entries from the start, or reallocate it each time you add an entry.mainrecursively! Use loops.std::vectoris the simple solution.