Function Pointer Arrays

What Is the Definition of an Array?

An array is an ordered list of same-type elements stored side by side and accessed by index. Here is the definition, the key terms, and how it applies in C++.

On this page
  1. The short definition
  2. Key terms
  3. Declaring an array
  4. Index and size
  5. How arrays differ from related types
  6. Elements can be more than numbers

The short definition

An array is an ordered collection of elements that all have the same type. The elements are stored one after another in memory, and each one is reached by its index. In C and C++, a built-in array has a fixed number of elements, set when you declare it.

Key terms

  • Element: one value stored in the array.
  • Index: the position of an element. Indexes start at 0 in C and C++.
  • Size: the number of elements the array holds.
  • Element type: the type shared by every element, such as int or double.

For double prices[4];, the element type is double, the size is 4, and the valid indexes are 0 through 3.

Declaring an array

The general form is the element type, the name, and the size in square brackets:

type name[size];

Two concrete examples:

double prices[4] = {1.25, 2.50, 3.75, 5.00};
char letters[3] = {'a', 'b', 'c'};

The initializer list is optional. A local array declared without one holds indeterminate values until you assign them.

Index and size

prices[1] is the second element, which is 2.5. A C-style array has no size() member, so your code either keeps the count itself or computes it with sizeof(prices) / sizeof(prices[0]) in the same function where the array is declared.

  • C-style arrays have a fixed size, no size member, and no bounds checks.
  • std::array, added in C++11, has a fixed size like a C-style array, but it reports that size through size(), and at() checks the index.
  • std::vector can grow and shrink while the program runs.

The c std::array topic covers the fixed-size type in more depth.

Elements can be more than numbers

Element types are not limited to built-in types. An element can be a struct, which is the idea behind array of structs in c, or a pointer to a function with a matching signature, which leads to c array of function pointers.

The complete guide to function pointer arrays

Arrays of Function Pointers in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

List vs Array in C++

Compare C++ arrays, std::array, std::vector and std::list by memory layout, element access and insertion cost, with code and a simple rule for choosing.

List vs Array 5 min read

std::optional in C++

std::optional in C++17 holds either a value or nothing. Learn how to check it, read it safely with value_or and return it from a function, with examples.

std::optional 4 min read

NULL vs nullptr in C++

NULL is an older macro, usually defined as 0. nullptr, added in C++11, is a typed null pointer that avoids overload surprises. Here's how to choose.