View RSS Feed

Development Team Blog

AddressOf() does/did not work as expected with String[]

Rate this Entry
A while ago I received a question about why the following code is not working as expected:

String[] listData
Move (SendMessage(hWnd, LB_ADDSTRING, 0, AddressOf(listData[iIndex]))) to iRetval
It's a little tricky, but the code is expecting a pointer to a null terminated C-style string. And usually AddressOf() will produce that with a local string variable. But in this case AddressOf() actually returns a pointer to the iIndex'th element in the array, which isn't really the same thing due to internal workings of arrays and strings.

A simple workaround is of course to copy the string into a local variable first, and then get the address of the local string:
Move listData[iIndex] to sData
Move (SendMessage(hWnd, LB_ADDSTRING, 0, AddressOf(sData))) to iRetval
So why wasn't AddressOf() returning the expected address? First of all, this behavior is changed in VDF 16.0, so that it actually returns the address that most people would expect. But in prior versions it returns the address of the array element. And as we learned in a previous article, String variables are dynamic, so an array element is really just a pointer to the string. Therefore a pointer to the array element is like a pointer to a pointer, and so AddressOf() wasn't returning the value you were expecting. But it gets even more complicated than that, as the string also holds the length encoded in the first 4 bytes, so another adjustment has to be made before returning the address.

All of this is just internal implementation details that you don't really have to deal with, but I'm telling you anyway because it's a technical blog. And now in VDF 16 it just returns the address you expected in the first place, rather than the address of the element. What if you really want the address of the element then? Then you're out of luck, and that's the trade-off for the change in behavior to make it work like most people expect most of the time. Actually, there are other ways to get that information too, but it's too complicated to get into right now.


  1. Frank Cheng's Avatar
    Very nice!