1: // Filename: PTR_EX7.CPP 2: // Purpose: Illustrates a dynamic array of (BankAccount) structs. 4: #include <iostream> 5: using namespace std; 7: int main() 8: { 9: cout << "\nThis program illustrates a dynamic array of structs. " 10: << "\nStudy the source code and the output simultaneously.\n\n"; 12: struct BankAccount // This struct definition would be 13: { // outside main if it were going to 14: int idNum; // be used by several functions, but 15: char kind; // can also appear inside main since 16: double balance; // it is only going to be used here. 17: }; 19: // Declare and initialize a 3-element array of type BankAccount. 20: BankAccount accounts[3] = { { 123, 'C', 199.99 }, 21: { 456, 'S', 898.98 }, 22: { 789, 'C', 321.45 } }; 24: // Use a BankAccount pointer to access and display the values 25: BankAccount* baPtr = accounts; 26: for (int i = 0; i < 3; i++) 27: { 28: cout << baPtr->idNum << " "; 29: cout << baPtr->kind << " "; 30: cout << baPtr->balance << " " << endl; 31: baPtr++; 32: } 33: cout << endl; 36: // Create a dynamic 3-element array of type BankAccount: 37: BankAccount* newAccounts = new BankAccount[3]; 39: // Values for the dynamic array are those of the static array (modified): 40: for (int k = 0; k < 3; k++) 41: { 42: newAccounts[k].idNum = accounts[k].idNum + 2; 43: newAccounts[k].kind = accounts[k].kind == 'C' ? 'S' : 'C'; 44: newAccounts[k].balance = accounts[k].balance + 20.00; 45: } 47: // Display the values in the dynamic array using index notation 48: for (k = 0; k < 3; k++) 49: { 50: cout << newAccounts[k].idNum << " "; 51: cout << newAccounts[k].kind << " "; 52: cout << newAccounts[k].balance << endl; 53: } 55: delete [] newAccounts; 57: return 0; 58: }