### Struct array length as function parameter

I have a structure "employee" and array of the structure called "company".
We input 3 pieces of info for each person in company.
void printemployee couts the information of each person, but I'm not sure as
to how to put the length of the array in the function parameter.

I have to simple run printemployee in the main, and have all the inputted information in company be accessed in the main

Now heres the code:
{structure employee {
int a;
int b;
float c;
}

void printemployee(employee e, /* the size of the array company*/) {
//code to cout the information of the employees
}

int main() {
employee company[3];
for (int i = 0; i < 3; i++) {
cout << "Enter Employee" << i << "'s a, b, and c" << endl;
cin >> company[i].a >> company[i].b >> company[i].c;
i++;
}
printemployee(company, ????? );
}
 ``12345678`` ``````void printemployee( const employee *company, size_t n ) { for ( size_t i = 0; i < n; i++ ) { std::cout << company[i].a << ' ' << company[i].b << ' ' << company[i].c; std::cout << std::endl; } } ``````

`printemployee( company, sizeof( company ) / sizeof( employee ) );`
Last edited on
Could you explain why you multiply the employee by the company in the void parameter?
sizeof returns the size of the created array, then divides it by the returned size of the struct. In this case since you created the array to be three employees, the size is 36/12 = 3.
closed account (D80DSL3A)
The * in `const employee *company` isn't for multiplication. In this context it means that a pointer to an employee is to be passed.

This prototype should also work
`void printemployee( const employee[] company, size_t n )` where the [] indicates that an array of employees is being passed to the function. The const qualifier just means that the function "promises" not to change any employee data.
This construction

const employee *company

inside the parentheses of the function is not a multiplication. It is the declaration of the parameter. It declares the parameter as a pointer to const employee.

When you pass an array by value to a function (and as I understood you need to do this) it implicitly is converted to a poinetr to its first element. So for example the following declarations of the function are equivalent

void printemployee( const employee company[10], size_t n )
void printemployee( const employee company[], size_t n )
void printemployee( const employee *company, size_t n )

and declare the same functionn.

Last edited on
Topic archived. No new replies allowed.