Arrays in C++
- An array stores many values of the same type.
- Each value has an index.
- The first index is always
0.
Array of objects
The code creates three different kinds of arrays.
| Code | What is allocated? | Where is it allocated? | Is A() called? |
|---|---|---|---|
A arr1[3]; |
3 real A objects |
automatic storage, usually stack | Yes, 3 times |
A* arr2 = new A[4]; |
4 real A objects |
heap | Yes, 4 times |
A** arr3 = new A*[5]; |
5 pointers to A |
heap | No A objects are created |
arr1 is an array of objects.
This creates 3 A objects immediately. The default constructor A() is called once for each object.
arr2 is a pointer to the first object in a dynamic array.
This creates 4 A objects on the heap. The default constructor A() is also called once for each object.
Because arr2 uses new[], you must release it with delete[].
arr3 is different.
This creates an array of 5 pointers. It does not create any A objects. It only creates places that can store addresses of A objects.
Memory layout after this line:
At this stage, only the pointer array exists.
No A constructor was called for arr3.
To create real objects for arr3, each pointer must point to an object.
Memory layout after this code:
Use object from pointer array
arr3[0] is a pointer to A.
Use -> to call a method through the pointer.
This is the same as:
Read it like this:
Clean
Warning
If you use new, you must later use delete. If you use new[], you must later use delete[].
Pointer array with nullptr
A pointer can point to nothing.
That value is nullptr.
arr3 is the array of pointers.
arr3[i] is one pointer inside the array.
Before calling a method with ->, check that the pointer is not nullptr.
You can also write the same check shorter:
Both mean:
use the object only if the pointer points to a real object.
Modern C++: std::array
std::array is usually better than a C-style array when the size is fixed.
std::array helps because it manages the array lifetime automatically.
You do not call new.
You do not call delete.
When the std::array variable goes out of scope, all objects inside it are destroyed automatically.
This is safer than:
With new[], you must remember to write delete[]. With std::array, C++ does the cleanup for you.
Important: std::array has a fixed size. If you need the array size to change while the program runs, use std::vector.
std::array<int, 3> means:
an array of 3 integers.
Modern C++: std::vector
Use std::vector when the size can grow.
push_back adds a new value at the end.
Quick rules
| Need | Use |
|---|---|
| Fixed number of simple values | std::array<int, 3> |
| Number of values can grow | std::vector<int> |
| Fixed number of objects | std::array<Robot, 2> |
| Objects may be optional | array/vector of pointers |
| Beginner example only | C-style array is OK |
For real projects, prefer std::array and std::vector over C-style arrays.