Search code examples
c++arraysstructdynamic-memory-allocation

how to pass arbitrary array of structs to a function?


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();
    }
}

Solution

  • There are multiple problems with this approach to your code. It is actually very intuitive what you are trying to do, so I understand your confusion. However, the main issue is that the array which stores the friends are reallocated every time main() is called:

    aFriend *p_array=new aFriend[index];
    

    This means that it will actually be reset every time it's called, which doesn't seem to be what you want, as you want to keep your old registered friends. The variable index is initialized to be zero in the beginning - arrays are indexed from zero, but initialized by the size you want. That is:

    aFriend *p = new aFriend[1]
    

    Will create an array of size one, which the first element you can then access by p[0].

    For solving your problem, either you want to use std::vector to be an array which can change size, or you want to create "big enough" array in the beginning. You can not resize a standard array. As well, in order to avoid recalling main, you can use a while loop, with the condition of that (pick != 4).