An array organizes items sequentially, one after another in memory.
Each position in the array has an index, starting at 0. They are made in stack.
string carModels[3];
carModels[0] = "FORD";
carModels[1] = "TESLA";
carModels[2] = "SUZUKI";
A Dynamic Arrays is an array with a big improvement: automatic resizing.
One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time.
A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time. They are made in Heap.
How do Dynamic arrays work? - GeeksforGeeks
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
Typically an array has uniform objects, but if we generalize the objects (polymorphism being a fun thing)…. Well, one good one is a chess board, if you want 2D, with the object being “chess piece”. My favorite for class, though, is a filing cabinet. Each drawer is a row, and in each drawer are files that you have direct access to look at the contents. If you take something out you have to reorder the drawer and it can get messy, just as it would with a normal array, and you can reorder rows as well. Adding rows is possible, just as messily. Short answer, but there’s one. Though, to be fair, a filing cabinet is also more of an array of arrays, since there is no guarantee that each row has the same size. And, I wait for a student to point this out for extra points in class. :) -Quora (told you not to read)
int* ptr = new int;
// Do something with ptr
// ...
// Forget to delete ptr
In this example, the memory for the integer object is dynamically allocated, but the reference to that memory (ptr
) is not properly deallocated. This will result in a memory leak.
int* ptr = new int;
delete ptr;
// Do something with ptr
In this example, the dynamically allocated integer object is deleted, but the pointer ptr
is still pointing to the memory location where the object used to be. This is a dangling pointer, and dereferencing it (e.g. *ptr = 5;
) can lead to undefined behavior.
int* ptr;
// Do something with ptr