global array c++ code example

Example: how to define global array in c++ in a scope

class C {
 int [] x;

 void method A(int size)
 {
   x = new int[size];   // Allocate the array
   for(int i = 0; i < size; i++)
      x[i] = i;         // Initialise the elements (otherwise they contain random data)
   B();
   delete [] x;         // Don't forget to delete it when you have finished
                        // Note strange syntax - deleting an array needs the []
 }

 void method B()
 {
   int n;
   cin >> n;
   cout << x[n];
   // Be warned, if the user inputs a number < 0 or >= size, 
   // you will get undefined behaviour!
  }
}

Tags:

Cpp Example