user3706129
user3706129

Reputation: 229

Return reference to array of structs

I have defined a Struct:

struct sym{
  int data_onel;
  int data_two;
}

and I have function:

sym*& fillStruct(){
   sym array_of_struct[size];
   /.. fill array with data
   return *array_of_struct;   
}

Where I create an array of struct and fill structs with data. However I would like to return this arr in another function. e.g

bool another(){
   sym *next_array = fillStruct();
}

I want it to pass by reference so it won't get destroyed, but it keep throwing:

invalid initialization of reference of type 'Symbols*&' from expression of type 'Symbols'

How can I return array of structs from function then? with reference.

Upvotes: 0

Views: 54

Answers (1)

H. Guijt
H. Guijt

Reputation: 3365

Your fundamental problem is that you are trying to return a local array, which will never work no matter how you spin it. A better approach would be to use a vector; a vector can also be declared locally, but unlike your array, it can be returned.

vector<sym> fillStruct(){
   vector<sym> array_of_struct;
   /.. fill array with data
   return array_of_struct;   
} 

bool another(){
   vector<sym> next_array = fillStruct();
}

Upvotes: 3

Related Questions