Your source for ASP-related frequently asked questions and answers! : ASP FAQS : Arrays

Question: How is a two-dimensional laid out in memory?


This message is a replica of Bill Wilkinson's post to the ASP Messageboard on March 23rd, 2001

The memory for a two-dimensional array is laid out the same as single dimensional arrays. Except that the "rows" are themselves contiguous. (If you've not already read the FAQ "How is an array stored in memory? I am interested in learning about the internals of an array!" be sure to do so now before continuing on with this FAQ.)

To illustrate, let's say you do:

Dim ar(1,3)

Then in memory you would find all the elements, contiguously, in this order:

ar(0,0) -- ar(1,0) -- ar(0,1) -- ar(1,1) -- ar(0,2) -- ar(1,2) -- ar(0,3) -- ar(1,3)

So to find element ar(x,y), you can treat this as a single dimensioned array and find the element numbered as

y * ( UBOUND(ar,1) + 1 ) + x

See it? ar(1,2) -->> 2 * ( UBound(ar,1)+1 ) + 1 -->> 2 * 2 + 1 -->> element number 5 [starting at 0, of course].

If you go count to element number 5 in the list above, you will see that it is, indeed, ar(1,2).

So, to get the address of that element, you simply multiply *that* result by 16 and add it to the address of the start of the array.

Now...WHY is this scheme chosen by VBScript???

Simply so that ReDim Preserve is easier to implement!

Suppose you start with that array, above, and then do ReDim Preserve ar(1,5). What does the language have to do?

First, it allocates enough memory for the new array: 16 * 2 * 6 bytes (128 bytes). Then it simply copies the old array, starting at its starting address and FOR THE SIZE OF THE OLD ARRAY to the starting address of the new array. Presto! It is done! (well, the elements of the new array beyond the end of the old have to get zeroed out, but that's a detail.) If it did the memory layout any other way, ReDim Preserve would be a *LOT* more work! And note that, because of the stuff discussed above, none of the elements in the newly sized array need to be touched, at all! Primitive values (numbers, etc.) are of course still fine. And pointers to objects (including strings) are still...well...pointing to the right place!

[ I leave it as an exercise for the reader to figure out what the system does if the ReDim size is smaller than the old size. ]

FAQ posted by Bill Wilkinson at 3/23/2001 7:26:46 PM to the Arrays category. This FAQ has been viewed 53,696 times.

Copyright 2018 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers