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:
Regardless of how you declare these arrays, they’re arrays of
int — meaning, they are structured something like this in memory:
For example, it could look something like this in memory:
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).
You could, of course, store the addresses of integers, instead:
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.