| ex2-7.cpp - Example 2-7 Dynamic Memory Allocation - strings(2) |
// File: ex2-7.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
int i;
char ** names; // declare array of pointers to char
char temp[16];
int NumberOfNames = 7;
names = new char*[NumberOfNames];
// read in 7 names and dynamically allocate storage for each
for (i = 0; i < NumberOfNames; i++)
{
cout << "Enter a name => ";
cin >> temp;
names[i] = new char[strlen(temp) + 1];
// copy the name to the newly allocated address
strcpy(names[i],temp);
}
// print out the names
for (i = 0; i < NumberOfNames; i ++) cout << names[i] << endl;
// return the allocated memory for each name
for (i = 0; i < NumberOfNames; i++) delete [] names[i];
delete [] names;
return 0;
}