I am trying to enter data into a data structure after passing it by ref to a function. When I use a for loop to refer to the specific struct index, I just get a load of errors. I refer to it as I would any array address in the loop.
Next time, you should post what those errors are, with corresponding line numbers.
employee is the type you defined. Treat it just like int or any other type, as far as syntax goes.
int arr[6]; is an array of ints. How would you normally pass an array of ints into a function?
employee employee_records[6]; is an array of employees. Not a single employee, as Employee& would suggest.
An array decays into a pointer to that array when passed into a function (although the language is nice and still lets you use [] to denote that it's meant to be a pointer to an array instead of just a pointer, but the syntax is equivalent to "employee* records").
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void enter_data(employee records[])
{
for (int i = 0; i < no_of_records; i++)
{
cout << "Enter the ID" << endl;
cin >> records[i].id_number;
cout << "Enter the Name" << endl;
cin >> records[i].name;
cout << "Enter the rate" << endl;
cin >> records[i].rate;
cout << "Enter the hours worked" << endl;
cin >> records[i].hours;
}
}
Thanks very much! I was under the impression that the function would create a copy of the array in order to execute any instructions inside it. Hence I thought I should pass by reference. But I should try to use pointer notation to perhaps do it again?
Glad it works. Indeed, raw arrays are an exception to what might be intuitive because it actually passes just a pointer to the array instead of making a copy of each element.
If you used library data structures such as std::array or std::vector, you could have an object that behaves as you wish, where a copy is made if you don't pass it by reference.
You could make it a reference to a single employee object, but employee_records is not a single employee, it is an array. You'd have to pass employee_records[0] instead of employee_records itself to be able to pass a reference to an employee. But that's really complicated to work as array, since you'd have to then take the address of the reference to get the pointer, and then increment the pointer. Which is a mess to work with, so I don't suggest doing that.