0

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.

1
  • You are returning a reference to a pointer which points to something that has gone out of scope. You need to re-think your approach. Commented Mar 20, 2016 at 9:34

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.