ETAN
ETAN

Reputation: 3182

pass struct array to a function by reference

there have been a lot of resources on this but I could not really understand the concept of this.

Here is my attempt using pointers:

struct PEOPLE{
   int id;
   string name;
   float cash;
};

int main(){
   PEOPLE data[5];
   getdata(data);

   for(int i = 0; i < 5; i++){
      cout << data[i].id << " " << data[i].name << "  " << data[i].cash;
   }
   return 0;
}

void getdata(PEOPLE &*refdata[5]){
    refdata[0].id = 11;
    refdata[0].name = "John Smith";
    refdata[0].cash = 200.30;
    //and so on for index 1,2,3,4
}

Is this approach correct, I doubt it will work.

Upvotes: 0

Views: 100

Answers (2)

yosim
yosim

Reputation: 503

You can simply define it as:

void getdata(PEOPLE refdata[])

and call:

 getdata(data);

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

This would work for arrays of a size known at compile time:

template<size_t N >
void getdata(PEOPLE (&refdata)[N] )
{
   refdata[0] = ....;
}

To restrict to size 5,

void getdata(PEOPLE (&refdata)[5] )
{
   refdata[0] = ....;
}

Upvotes: 1

Related Questions