sábado, 30 de noviembre de 2013

Dynamic Arrays

A dynamic array is an array whose size is determined when the program is running, not when you write the program.

Array variables are actually pointer variables that point to the first indexed variable. For example:

int a[10];
typedef int* IntPtr;
IntPtr p;

Variables a and p are the same kind of variable

  • Since a is a pointer variable that points to a[0], 
  • p = a; 
  • causes p to point to the same location as a
  • Pointer variable p can be used as if it were an array variable.
  • Variable a can be used as a pointer variable except the pointer value in a cannot be changed.


Normal arrays require that the programmer determine the size of the array when the program is written. Dynamic arrays can be created with just the right size while the program is running.

Dynamic arrays are created using the new operator.  For example, to create an array of 10 elements of:



type double:
typedef double* DoublePtr;
DoublePtr d;
d = new double[10];

d can now be used as if it were an ordinary array!

When finished with the array, it should be deleted to return memory to the freestore.  For example:

delete [] d;

  • The brackets tell C++ a dynamic array is being deleted so it must check the size to know how many indexed variables to remove.

  • Pointer Arithmetic:

    Arithmetic can be performed on the addresses contained in pointers.
    You can add and subtract with pointers:
    • The ++ and - - operators can be used
    • Two pointers of the same type can be subtracted to obtain the number of indexed variables between.
    • This code shows one way to use pointer arithmetic:
                             for (int i = 0; i < array_size; i++)
                                   cout << *(d + i) << " " ;      // same as cout << d[i] << " " ;

    Multidimensional Dynamic Arrays:

    To create a 3x4 multidimensional dynamic array
    • View multidimensional arrays as arrays of arrays
    • First create a one-dimensional dynamic array
      • Start with a new definition:
        • typedef int* IntArrayPtr;
      • Now create a dynamic array of pointers named m:
        • IntArrayPtr *m = new IntArrayPtr[3];
    • For each pointer in m, create a dynamic array of int's
        • for (int i = 0; i<3; i++)
        • m[i] = new int[4];
    • The dynamic array created on the previous slide 
    • could be visualized like this:


    Deleting Multidimensional Arrays:

    To delete a multidimensional dynamic array, each call to new that created an array must have a
    corresponding call to delete[ ].  For example:

    for ( i = 0; i < 3; i++)
    delete [ ] m[i];           //delete the arrays of 4 int's
    delete [ ] m;              // delete the array of IntArrayPtr's





    No hay comentarios.:

    Publicar un comentario