Returning an array of type struct

I have a struct that takes in values for name, id, salary, etc, called Emp. I have a function that creates an array, employee[5], and then uses a for loop to fill in all values. To return these values back to my main function, i use:

 
return employee[5];


my main function looks like this:
1
2
3
4
5
6
7
8
int main()
{
	Emp Employee;
	
	Employee[] = get_data(); // function to input values, mentioned above.
	print_data(Employee);
	return 0;
}


I am struggling to then pass this struct/array, to a new function, print_data.
currently:
prototype: void print_data(struct Emp[]);
main call: print_data(Employee);
function: void print_data(struct Emp Employee)

I don't believe this is quite correct, and any advice would be appreciated.

Thanks
Crimson
return employee[5];
This tries to return the 6th element in the array. Which doesn't exist. This is very bad.

The simplest thing to do is just use a vector. This is C++. Just use a vector. Not an array.

Also, in C++, you should be using "struct" only at the definition of the struct. I see you're using "struct" all over. This looks like C code. Is this C code?
Hey Repeater,

If I wanted to return the entire array, what would I need to use instead? And if I choose to make it a vector, would would the line be?

"you should be using "struct" only at the definition of the struct. " By this do you mean only at the very beginning where I set it up? I am only just starting to learn C++, in particular structs, so that might be why is doesn't look quite right.
Here is a grab-bag of example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <vector>  // include the right header
using std::vector; // vector lives in the std namespace

struct Employee   // struct is used here, and that's it.
{
  string name;
  string number;
};

vector<Employee> theVector; // This creates a vector of Employee objects. Currently size zero. Empty.
Employee anEmployee; // This creates an employee

theVector.push_back(anEmployee); // this copies that employee onto the end of the vector. Now the vector is size one

vector<Employee> theVector(5); // This creates a vector of Employee objects, size 5. Each Employee object needs the right data copied into it now


// Functions
 void print_data(vector<Employee> input_vector)
{
for (int i = 0; int i < input_vector.size() ; i++)  // NOTE: the vector know its own size
  {
    // do something with Employee object input_vector[i];
  }
}

Last edited on
Thanks Repeater, the same code is very helpful
Topic archived. No new replies allowed.