Monday, 30 April 2012

Dynamic Allocation for an Array in C++ ( new and delete )


#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

int main()
{
  const int MAX = 5;

  char B[81];
  char* C[MAX];
  int i;

  cout << "Enter " << MAX << " names." << endl;

  for (i = 0; i < MAX; ++i)
  {
    cout << endl;
    cout << "Name: ";
    cin.getarr(B, 81);

    C[i] = new char [strlen(B) + 1];
    strcpy(C[i], B);
  }

  cout << endl;
  cout << "Following are the names you entered." << endl << endl;
  for (i = 0; i < MAX; ++i)
    cout << endl << C[i];

  for (i = 0; i < MAX; ++i)
    delete [] C[i];

  cout << endl;
  return 0;
}

No comments:

Post a Comment