Dynamic 2d Array
Dynamic 2d Array
Ye
Dynamic Arrays
• Pointer arithmetic
• Two-dimensional dynamic array
Pointer Arithmetic
• Arithmetic (addition and subtraction) can be
performed on the addresses contained in pointers
– Using the dynamic array of doubles declared previously
(Dynamic 1-d array slide #7), recall that pt points to pt[0]
– The expression pt+1 evaluates to the address of
pt[1] and pt+2 evaluates to the address of pt[2]
• Notice that adding one adds enough bytes – the size of
the base type (in this example, double)
2
Pointer Arithmetic Operations
• You can add (+) and subtract (-)with pointers
– The ++ and -- operators can also be used
– Two pointers of the same type can be subtracted to
obtain the number of indexed variables between them
• The pointers should be in the same array
3
Allocating Memory for 2-d Dynamic Arrays
• To create a 4x3 (4 rows x 3 columns) two-dimensional
dynamic array
– View the 2-d array as an array of arrays
– First create a one-dimensional dynamic array of pointers
• Start with a new definition:
typedef int* IntArrayPtr;
• Now create a dynamic array of pointers named matrix:
IntArrayPtr* matrix = new IntArrayPtr[4];
//The above two statements can be combined to: int** matrix = new int*[4];
– For each pointer in matrix, create a dynamic array of
integers:
for (int i = 0; i < 4; i++)
matrix[i] = new int[3];
4
• The dynamic array created on the previous slide
could be visualized like this:
These
boxes are
int type
5
Deleting the 2-d Dynamic Array
• To delete a multidimensional dynamic array
– Each call to new that created an array must have a
corresponding call to delete[]
– Example:
To delete the dynamic array shown on the previous slide: