DEV Community

Cover image for C++: A concise introduction to Arrays
Isaac Smith
Isaac Smith

Posted on

C++: A concise introduction to Arrays

An array is a collection of elements (values or variables) of the same type that are stored in contiguous memory locations and may be accessed individually using a unique identifier's index. The memory addresses are all next to one other, and the array's size is determined by the number of elements. The first or base address is the memory address of an array's first element. An index, which is usually a non-negative scalar number, is used to select individual objects. The index of an array's initial element is almost always zero. The array value is mapped to a stored object via an index. The following is an example of the mapping.

map(arrayName, index)  element
Enter fullscreen mode Exit fullscreen mode

An example of an array declaration.

datatype arrayName [elements];
Enter fullscreen mode Exit fullscreen mode

There are three types of arrays in C++; one-dimensional, two-dimensional and multidimensional array.

A one-dimensional is also called a linear array.

int myArray0[5] = {1, 2, 3, 4, 5};
Enter fullscreen mode Exit fullscreen mode

In a two dimensional array there are 'x' number of rows and 'j' number of columns. They are sometimes called matrices or tables.

int myArray1[2][2] = {{1, 2}, {3, 4}};
Enter fullscreen mode Exit fullscreen mode

A multidimensional array can have any number of dimensions.

int myArray2[2][2][2][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}
Enter fullscreen mode Exit fullscreen mode

Arrays can be used to implement other data structures such as lists, hash tables, stacks and strings.

Happy Coding.

Top comments (2)

Collapse
 
huncyrus profile image
huncyrus

Near simple types, it is possible to use another lists - what behave like arrays - e.g.: iterable lists like std::list or std::(de)queue.

Collapse
 
sandordargo profile image
Sandor Dargo

But if you really need something that behaves like arrays, use std::array from the <array> header.