简体   繁体   中英

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.

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] = ....;
}

You can simply define it as:

void getdata(PEOPLE refdata[])

and call:

 getdata(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM