I am trying to implement a simple constant size stack that holds constant size strings.
It has Pop method that returns empty string until stack is full and then it starts returning oldest items on the stack. It works fine the first time it has to return the item, but then it starts returning rubbish.
The problem is in CopyMemory API call.
However, copying array in a loop beats the purpose of the stack, since it has to be efficient.
Where lays the problem? Is there some other efficient way to copy array?
I have implemented it this way (see attached snippet and ignore colouring)
'start of class
Private stack() As String
Private size_ As Integer
Private count_ As Integer
Public Sub Initialize(size As Integer)
size_ = size
ReDim stack(size_ - 1)
Public Function Pop(push As String) As String
If count_ < size_ Then
stack(count_) = push
count_ = count_ + 1
Pop = ""
Dim popResult As String
popResult = stack(0)
Dim tempStack() As String
ReDim tempStack(size_ - 1)
'copy to temp array but leave out the oldest item (source is stack(1))
CopyMemory VarPtr(tempStack(0)), VarPtr(stack(1)), Len(popResult) * (size_ - 1)
'put new item at the end of stack
tempStack(size_ - 1) = push
'copy temp array back to stack
CopyMemory VarPtr(stack(0)), VarPtr(tempStack(0)), Len(popResult) * size_
Pop = popResult
Public Function ToArray() As String()
ToArray = stack()
'end of class of class
' I have declared CopyMemory API function in module as this:
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(ByVal pDestination As Long, ByVal pSource As Long, ByVal ByteLen As Long)
'Finally, here is some test code, paste it into a form:
Private Sub testStack_Click()
Dim stack As New ConstSizeStringStack
Dim i As Integer
For i = 0 To 8
Dim itm As String * 10
itm = "STR" & CStr(i)
'prints nothing after returning STR0 and the content of internal
'stack array in debbuger shows error
Dim strs() As String
strs = stack.ToArray
Dim j As Integer
For j = LBound(strs) To UBound(strs)