Tmp2

From assela Pathirana
Revision as of 15:35, 9 April 2007 by Root (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Good practice in Coding (in C++/C)

  • Use pointers sparingly, there are many situations where they have good alternatives. Make a concious effort to find these alternatives if at all possible. One good example is use of vectors instead of dynamic arrays.
int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0;i<n;i++){
    cin >> a[i];
}
. . .  
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.

vector <int> a; int n; // Size needed for array cin >> n; // Read in the size for (int i=0;i<n;i++){

   int tmp;
   cin >> tmp;
   a.push_back(tmp);

} a.erase();