/* Filename: PtrsToStructs.cpp * * Author: Br. David Carlson * * Date: Oct 8, 2016 Revised: Oct 12, 2016 * * Description: This program sets up a structure type called EmployeeType and then creates * a type for a pointer to a structure of this type. Any structure of the given type holds * the ID number, name, and wage rate for one employee. This program dynamically allocates * space for a new EmployeeType structure, uses the pointer to put data into the 3 fields * of the structure, and then uses a pointer to print the data. Two ways of doing all of * this are illustrated. */ #include #include using namespace std; struct EmployeeType { string Name; int IDNum; float WageRate; }; typedef EmployeeType * EmployeePtrType; int main(void) { // First way to use a pointer to dynamically allocate a structure and then use the structure to hold data. EmployeePtrType EmployeePtr; EmployeePtr = new EmployeeType; EmployeePtr->Name = "Sally Keffer"; EmployeePtr->WageRate = 22.95; EmployeePtr->IDNum = 6438; cout << "Information on Employee:" << endl << endl; cout << "ID number: " << EmployeePtr->IDNum << endl; cout << "Name: " << EmployeePtr->Name << endl; cout << "Wage rate: " << EmployeePtr->WageRate << endl << endl; delete EmployeePtr; // Don't forget to recover the allocated space when you are done with it. // Second way to use a pointer to dynamically allocate a structure and then use the structure to hold data. // This way is preferred in that it throws an exception if the new operator fails to allocate the memory space. EmployeePtrType p; try { p = new EmployeeType; } catch (...) { cerr << "Could not allocate memory for a new EmployeeType structure." << endl << endl; exit(1); } p->Name = "Sam Snead"; p->WageRate = 20.45; p->IDNum = 1207; cout << "Information on Employee:" << endl << endl; cout << "ID number: " << p->IDNum << endl; cout << "Name: " << p->Name << endl; cout << "Wage rate: " << p->WageRate << endl << endl; delete p; // Don't forget to recover the allocated space when you are done with it. return 0; }