Revision as of 10:40, 15 November 2017 by (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

An array is a contiguous sequence of objects of the same type. Each element of such collection can be referenced by an identifier, referring to the beginning of the array and an index.

Arrays are useful to store a potentially large number of values without needing to declare lot of different variables. For example, we only need one variable to represent an array of 10 integers, whereas 10 variables would be needed if we didn't use an array.

Arrays are defined as follows:

int a[7];

The above defines an array of 7 elements of type int. The number of elements must be known at compile-time. If the length is not known at compile-time, then one of the following approaches can be employed to get equivalent functionality:

  • Use a standard container such as std::vector. This is the path you should take most of the time, unless you have a good reason.

Individual elements can be referred to using the square braces, or, more formally, subscription operator: a[0] refers to the first element, a[1] refers to the second and so on. Note, that numbering starts at 0 rather than 1. For example:

a[4] = 3;      // assigns 3 to the fifth element
int x = a[3];  // assigns the fourth element to x

The image below illustrates an array and its relation to the C++ syntax. Each panel represents an element in the array a


As with regular variables, elements in an array must be always initialized before use. Otherwise, their contents will be undetermined which is majority of programs. There are several specific exceptions to this rule, but for now, this is all we need to know.

Arrays can be initialized by either of the following approaches:

  • Setting the values in a loop or using std::fill(). This works well when it's easy to compute the values.
  • Setting the values by ??? between braces ( { } ). This is useful when the values can't be easily computed.

Below is an example that demonstrates several simple uses of arrays:

#include <iostream>
#include <memory>
#include <cstddef>
// to illustrate the proper method to get the length of an array
// note: this is prefered over a similar macro implmentation
// "sizeof(array) / sizeof(array[0])"
// this is only possible for arrays of known size (not dynamically allocated)
// which is type safe over the macro implementation
//  - macro compiles when used on dynamic allocated arrays, though returns invalid size
template<typename T, std::size_t N>
std::size_t LengthOf(T (&)[N]) { return N; }
class ExpensiveObject
	ExpensiveObject() { std::cout << "I am expensive!" << std::endl; }
int main()
	const int MaxSize = 5;
	int array1[] = { 1, 2, 3 };
	int array2[MaxSize];
	std::cout << "Length of array1: " << LengthOf(array1) << std::endl;
	std::cout << "Length of array2: " << LengthOf(array2) << std::endl;
	std::cout << "\tContents of array1:" << std::endl;
	for(auto& v : array1) std::cout << v << std::endl;
	// note: random uninitialized contents
	std::cout << "\tContents of array2:" << std::endl;
	for(auto& v : array2) std::cout << v << std::endl;
	std::cout << "\tExpensive test 1:" << std::endl;
	ExpensiveObject array4[2];
	std::cout << "\tExpensive test 2:" << std::endl;
	// important: note the [] in the template parameter,
	std::unique_ptr<ExpensiveObject[]> array5( new ExpensiveObject[3] ); 


Length of array1: 3
Length of array2: 5
Contents of array1:
Contents of array2:
	Expensive test 1:
I am expensive!
I am expensive!
	Expensive test 2:
I am expensive!
I am expensive!
I am expensive!

Multidimensional arrays

A multidimensional array is very similar to a conventional array. Multidimensional arrays are stored as a continuous sequence of objects of the same type, just as an array is. The important thing to note are the numbers that define how large to make each dimension. Because of this it is not possible to pass a multidimensional array without also providing the length of its dimensions.

Multidimensional arrays are defined and passed to functions as follows:

int a[7][7];
int b[7][8][8];
// our function definitions
void foo(int array[][7], int size); 
void bar(int array[][8][8], int size);
foo(a, 7);
bar(b, 7);

Automatic conversion to pointers