42
pointers. This list of pointers will comprise the “rows” of the array. Line 5 just declares
some working variables that are used in the For-Next loops later in the program.
Line 8 creates the rows of the array by allocating a memory segment that will
contain 4 integer pointers, which are initialized in lines 11 through 13. Remember that
the index method of accessing a pointer automatically does the pointer arithmetic for
you. The code in lines 11 through 13 iterates through the memory segment created in
line 8 and initializes the memory segment with pointers to memory segments that will
contain integers. In other words, you have a pointer that is pointing to a list of pointers.
These newly created memory segments are the columns for each row. Each column index
will be a pointer to a memory location containing an integer.
Lines 16 through 20 add some random numbers to the memory array. Notice that
by using the indexing method you can access the memory array just like a normal array. i
points to the row (the list of pointers) and j points to the individual columns within that
row which contain the integer data. The same method is used in lines 23 through 27 to
print out the array values.
Lines 30 through 32 free the individual rows of memory that were created in line 8. It is
important that each row be freed before freeing myMemArray. If you were to just free
myMemArray, the rows would still be in memory, but unaccessible, causing a memory
leak. Once all the rows have been freed, myMemArray can be freed in line 34. Since the
program is terminating, Deallocating the memory is not strictly required in this instance,
but if you needed to reuse the memory, then you must Deallocate in the method
described, otherwise you will get a memory leak while the program is running. Lines 36
and 37 close the program in the usual way.
Running the program should produce a result similar to the following.
i,j=0,1MemArray=5
i,j=0,2MemArray=1
i,j=0,3MemArray=8
i,j=0,4MemArray=5
i,j=1,0MemArray=4
i,j=1,1MemArray=3
i,j=1,2MemArray=8
i,j=1,3MemArray=8
i,j=1,4MemArray=7
i,j=2,0MemArray=1
i,j=2,1MemArray=8
i,j=2,2MemArray=7
i,j=2,3MemArray=5
i,j=2,4MemArray=3
i,j=3,0MemArray=0
i,j=3,1MemArray=0
i,j=3,2MemArray=3
92