Home / code / cpp

Arrays in C++

The explanation here is very short and incomplete, if you want a full explanation on arrays and pointers, read a book.

An array is actually a table of value's.

Example:
#include <iostream.h>

void main()
{
  int a[5]; //declaration of the array
  int i;

  for (i=0;i<5;i++)
  {
    cout << i <<"e number: ";
    cin >> a[i];
  }

  cin.get();
  int som=0;
  for(i=0;i<5;i++) sum +=a[i];

  cout << endl << "Total: " << sum << endl;
  cin.get();
}

Upper limit
The upper limit is the highest value the index may have.
In the example we have int a[5]; so the highest value can be 4 (0-4), computers start counting from 0.

In c++ there is no array bounds checking, so you don't get a warning when you take a index higher then the maximal.

Initialization

int a[5]={12,23,24,45,56};
But you can always assign a value later:
array[index]=value;

Sometimes you don't know how many variables you are going to store in the array. Then you can use Dynamic arrays.
With dynamic arrays you can request memory for your new array when the program is running.
If you already understand pointers, you should understand the following code. For everyone else, copy - past.

int number;
cout << "How many numbers do you want ?";
cin >> number;

int * p;
p = new int[number];  /*Asking for memory*/

sum=0;
for(int i=0;i<number;i++)
{
  cout << "Enter the " << (i+1) << "th number in";
  cin >> p[i];
}
cin.get();

for(int i=0;i<number;i++) sum += p[i];
cout << "The average is " << double(sum)/number;

delete[] p;  /*Releasing the memory*/

With int * p;, you make a pointer of the type int.

With this line p = new int[number];, you request a array of integers with the size of numbers.

delete[] p; Deletes p and releases the memory, really important if you want to prevent memory leaks.

 

TOP

Latest script:

 

Books: