Don't like ads? PRO users don't see any ads ;-)
Guest

Mail Pointer Array

By: a guest on Apr 29th, 2012  |  syntax: C++  |  size: 1.08 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Mail
  5. {
  6. public:
  7.     Mail() {}
  8.     Mail(int c) { cost = c;}
  9.    
  10.     int getCost() { return cost; }
  11.    
  12. private:
  13.     int cost;
  14. };
  15.  
  16. int main (int argc, const char * argv[])
  17. {
  18.     const int MAX_MAIL = 20;
  19.    
  20.     // Make an array of MAX_MAIL Mail pointers. The () at the end sets the array
  21.     // elements to 0 (i.e. null pointers). You could always iterate over the
  22.     // pointers and set them to 0 instead.
  23.     Mail **m = new Mail*[MAX_MAIL]();
  24.    
  25.     // Create MAX_MAIL new Mail items, and assign their pointers to the array.
  26.     for (int i = 0; i < MAX_MAIL; i++)
  27.         m[i] = new Mail(i);
  28.    
  29.     // Do stuff with the array here........
  30.    
  31.     // Go through all pointers, delete them if they're not null.
  32.     for (int i = 0; i < MAX_MAIL; i++)
  33.     {
  34.         if (m[i] != 0)
  35.         {
  36.             delete m[i];
  37.             m[i] = 0;
  38.         }
  39.     }
  40.    
  41.     // Delete the dynamically allocated array. This differs to deleting the
  42.     // individual Mail* array elements.
  43.     delete[] m;
  44.    
  45.     return 0;
  46. }