I was recently asked:

“Do arrays in C++ store the actual value in the array, or their pointers in memory?”

I get a lot of programming questions like this, as a developer who works several community projects, and as a programming mentor. In this new series of articles, which I’m calling “QIG” (“Questions I Get”), I’m writing down the answers I give to common questions I get about programming, C++, architecture, and so on. If one person has that question, others probably do, too!


The simple answer is: C++ arrays store exactly what you tell them to store. If you declare an array of integers, your array will hold integers (not addresses of integers).

For the sake of completeness, I’d like to expand on this with some examples. Say you’ve got an array of integers:

int my_array[15];
// or
std::array<int, 15> my_array;
// or
int* my_array = new int[15];
// or
std::vector<int> my_array;

Regardless of how you declare these arrays, they’re arrays of int — meaning, they are structured something like this in memory:

[int, int, int, ... ]

For example, it could look something like this in memory:

1  2  35  77  -35  123

They are a contiguous (meaning one-after-the-other) array of integers, where the values are the values of the integers.

You may access the values in the array via a pointer, but the array itself stores integers directly (or whichever other type you are storing).


Sidenote

You could, of course, store the addresses of integers, instead:

int* my_array[15];
// or
std::array<int*, 15> my_array;
// or
int** my_array = new int*[15];
// or
std::vector<int*> my_array;

In this example, the arrays store pointers to integers, meaning they store the addresses of integers. The use-cases for this are very different from the ones of a normal array of integers. Still, it’s useful to illustrate that you can have an array of anything, and it will be an array holding those types directly, without indirection.