Dynamic Arrays

This is a short tutorial on Dynamic Array allocation in C++, written sometime in 2003/04.


This tutorial assumes that you have prerequisite knowledge about arrays, their use, purpose and declaration in C and C++. You should also have a fair idea of how to use pointers. Pointers form the foundation of dynamic memory allocation. You'll see how. A standard C/C++ compiler such as Visual C++ 6.0 or Turbo C++ is recommended.

If you come across any inaccuracies, deficiencies or incorrect information, please let me know. Some programs or code mentioned here may run on my system, but not on yours, so if you face any such problems, please let me know so that they can be mentioned at the end of this tutorial to help other users. Platform independence is desired but not always achievable.


Why would I need one?

Let me answer this question with a simple example. Suppose are a game programmer who has to store structural information about a building or vehicle that is being used in a game. Now, when you're sitting coding with a cup of coffee on your computer, you don't know how detailed it has to be. This would depend on the user's choice and also possibly on his/her graphics card's rendering abilities. One way is to store ALL possibilities in a file and call a specific one, based on a preliminary hardware test or user choice (input). But for modern day games, this can be demanding with so many graphics cards, monitors and resolutions out there. Also, there is a great deal of information to be stored such as user scores, graphics rendering variables, sounds, textures, etc. It simply isn't preferable to have static arrays to store data because you would be using a lot of system resources just to store data, but using less than half of what you've stored. There's got to be a way to allocate memory as the program executes, depending on the requirements for that session and that session only.

If you can't get the game example, here's a simpler one: you've got to create a database of your classmates, their grades, phone numbers and addresses and you can't declare 50+ arrays for marks, grades, etc. because you've got to show that you're smart. What would you do? You should have a system by way of which you can continue input to the user and stop when the input is finished. There are two ways to do this: dynamic arrays and linked lists. We won't be talking about linked lists for now.

Let's jump into some code fragments and see how we can do this.


Declare a 1-D dynamic array

In C++, we use the new statement in conjunction with the datatype of our choice. Effectively, we declare a pointer array, that points to specific memory locations. This is how we do it for an dynamic int array:

datatype functionname(independent variable list)
{
   .
   .
   .
   int *p = new int[p_size];
   .
   .
   .
}

So, new is used as:

datatype *ptrName = new dataype[size of array];

Some programmers like to define a pointer to an array first by:

datatype *ptrName;

and then use

*ptrName = new datatype[size of array];

which amounts to the same thing. Now you can do anything with this array. To access individual members for an array defined in the code above, you would use p[i] where i is the index variable in the range: 0<= i <=(imax-1).

In C, we use malloc to allocate memory dynamically. You must remember however, that in both C and C++, the size of such an array has to be defined before you can malloc or new, respectively. Of course, the size has to be an int, so I like to initialize it to 0, do malloc/new and then input the size (using cin or std::cin). Include malloc.h and/or stdlib.h in all programs that use malloc. Here's the C code for int:

datatype functionname(independent variable list)
{
 .
 .
 .
 
 int p;
 p = (int*)malloc(p_size*sizeof(int));
 .
 .
 .
 
}

Note the use of the sizeof(datatype) operation. This tells us the size in bytes assigned to a specific data type. p_size*sizeof(int) would tell the computer how much memory has to be reserved in bytes for this array. Dynamic Arrays (darray) as defined in C and C++ are accessed similarly. Essentially, malloc is a better way to allocate memory dynamically, even in C++. Some folks prefer to use multiple pointer arrays since declaring darrays is so easy.

Freeing Allocated Memory

There's a catch. By declaring a darray using new or malloc, you actually reserved memory. But when you're done with the array, you have to discard this memory space. Modern compilers may take care of this, but it is highly recommended that you delete the allocated memory space. In C++, the delete statement is used in conjunction with a NULL assignment operation to remove all traces of the array. Remember this as a good coding principle: for every new, there's got to be a delete and a NULL. Here's how we do it:

datatype functionname(independent variable list)
{
 .
 .
 .
 
 int *p = new int[p_size];
 
 // p usage code starts here
 .
 .
 .
 // p usage code ends here
 
 delete [] p;
 p[] = NULL;
 
}

For C: A similar memory freeing technique exists for C as well. We use the free statement. Remember this as a good coding principle: for every malloc, there's got to be a free. Here's how we do it:

datatype functionname(independent variable list)
{
 .
 .
 .
 
 int p;
 p = (int*)malloc(p_size*sizeof(int));
 
 // p usage code starts here
 .
 .
 .
 // p usage code ends here
 
 free(p);
 
}

NOTE ON TWO DIMENSIONAL ARRAY ALLOCATION:

Below is the self explanatory code to allocate a 2D array (matrix) at runtime. The link is http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20724866.html. Source provided by Miles Van Pelt.

int rowMax, kolMax ;
 
int *matrix = new int[rowMax][];
 
for(i=0;i<=rowMax-1;i++)
{
   for(j=0;j<=kolMax-1;j++)
   {
         matrix[i][j]= new int[y];
   }
}

Freeing memory is something we've been unsuccessful with, primarily because Windows 98 freezes the compiler during the process forcing a brute force Alt+F4 exit.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License