Retrieving an array's pointer
Posted on 2003-02-23
Before the question, I need to be sure we're straight on a few facts:
VISUAL BASIC & ARRAY POINTERS
Dim MyArray(2) As String
MyArray(0) = "jim"
MyArray(1) = "joe"
MyArray(2) = "jon"
In memory the array is comprised of three 4 byte elements. Each element is a pointer to the actual string. To get the element's address in memory you use VarPtr(MyArray(X)). The easy way to get that element's value you may use StrPtr(MyArray(X)).
So here we have an array floating in memory:
Address: VarPtr0 VarPtr1 VarPtr2
Value: StrPtr0 StrPtr1 StrPtr2
It's an easy thing to replace the values for each element so that each element points to a different string. You can find numerous articles on string sorting algorithms using such a technique. However, I need the array variable itself to point to a completely different array. Now of course, we could do something like this:
'We create an array with a null pointer
Dim Array1() As String
'We create an array with a pointer to an allocated array
'(although, each element is a null pointer)
Dim Array2(2) As String
Array1 = Array2
Array1 now has 3 elements. Seems like we did a pointer assignment. But we didn't. Cause if you do this test:
Debug.Print VarPtr(Array1(0)), VarPtr(Array2(0))
You'll find that the element addresses are completely different. If we DID assign a pointer to the entire array to Array1, then if you modified Array2, you'll be modifying Array1. But that is not the case. Instead, VB copied the array.
I have a dynamic 3 dimensional array. I am not allowed to ReDimension the array's first 2 dimensions. However, it is required that this array be completely dynamic, and I've been searching for workarounds. My favorite idea is to create a new array by the required dimensions and swap the 2 array variable's pointers. That way when the routine ends, VB will free up the memory pointed to by the temporary array variable, and leave my original array variable, and its new contents, alone.
Nice story huh? Well, I know the theory works cause it works like that with individual elements. You can swap element pointers and have a happy day.
I can't get the address of an array variable.
The variable MyArray points to the first element of the actual allocated array. The VALUE of MyArray isn't hard to get. All you have to do is VarPtr() the first element. But I don't have the ADDRESS of MyArray (ptr1 in the diagram). I need that address in order to change the value to the pointer of a different array. VarPtr(MyArray) does not work. I get type errors.
*whew* that's it. Sorry for being so verbose, but I wanted to be absolutely clear.