Search code examples
arraysvb6

How do I determine if an array is initialized in VB6?


Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound. How do I do this?


Solution

  • Here's what I went with. This is similar to GSerg's answer, but uses the better documented CopyMemory API function and is entirely self-contained (you can just pass the array rather than ArrPtr(array) to this function). It does use the VarPtr function, which Microsoft warns against, but this is an XP-only app, and it works, so I'm not concerned.

    Yes, I know this function will accept anything you throw at it, but I'll leave the error checking as an exercise for the reader.

    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
      (pDst As Any, pSrc As Any, ByVal ByteLen As Long)
    
    Public Function ArrayIsInitialized(arr) As Boolean
    
      Dim memVal As Long
    
      CopyMemory memVal, ByVal VarPtr(arr) + 8, ByVal 4 'get pointer to array
      CopyMemory memVal, ByVal memVal, ByVal 4  'see if it points to an address...  
      ArrayIsInitialized = (memVal <> 0)        '...if it does, array is intialized
    
    End Function