Here's some code I wrote up in C++ that does the basics.
#include <iostream>
int main(int argc, char *argv[])
{
int* my_dynamic_array;
int size;
std::cin >> size;
my_dynamic_array = new int[size];
for (int k=0; k<size; k++)
my_dynamic_array[k] = k;
for (int k=0; k<size; k++)
std::cout << my_dynamic_array[k] << std::endl;
delete[] my_dynamic_array;
return 0;
}
Okay, so here's what's going on in this code. We're prompting for the size of the array using std::cin and then using the new keyword to dynamically allocate some memory for the array. There's some details here that make it seem a little weird at first; it's what seems to cause confusion with a lot of new C++ developers.
So first we declared our dynamic array with a pointer instead of the array declaration, e.g. we used int *my_dynamic_array
instead of int my_dynamic_array[]
. At first this seems kind of trivial, but there's something that you need to understand about what's going on in C and C++.
When you statically declare an array, you are telling the program that you want to set aside that memory for you to use. It's actually there; it's yours for you to start using. When you dynamically create an array, you start with a pointer. Pointers are just a reference to some memory. That memory isn't allocated yet. If you try to access something in it with, say, my_dynamic_array[3]
, you'll get a nasty error. That's because there's nothing actually in memory at that location (at least nothing that has been given to the program to use).
Also note the use of delete[]
instead of delete
. That's the way you free up the memory when you're done with the array.
If you're doing this in C, you can pretty much think of this the same way, but instead of new
and delete[]
you have malloc
and free
.
Knowing the subtle differences between dynamic arrays and pointers is tricky. It took me a while before I fully understood what was going on. Good luck and keep at it.