ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6 -
i'm using vb6 , need redim preserve multi-dimensional array:
dim n, m integer n = 1 m = 0 dim arrcity() string redim arrcity(n, m) n = n + 1 m = m + 1 redim preserve arrcity(n, m)
whenever have written it, following error:
runtime error 9: subscript out of range
because can change last array dimension, in task have change whole array (2 dimensions in example) !
is there workaround or solution this?
as correctly point out, 1 can redim preserve
last dimension of array (redim statement on msdn):
if use preserve keyword, can resize last array dimension , can't change number of dimensions @ all. example, if array has 1 dimension, can resize dimension because last , dimension. however, if array has 2 or more dimensions, can change size of last dimension , still preserve contents of array
hence, first issue decide whether 2-dimensional array best data structure job. maybe, 1-dimensional array better fit need redim preserve
?
another way use jagged array per pieter geerkens's suggestion. there no direct support jagged arrays in vb6. 1 way code "array of arrays" in vb6 declare array of variant
, make each element array of desired type (string
in case). demo code below.
yet option implement preserve
part on own. you'll need create copy of data preserved , fill redimensioned array it.
option explicit public sub testmatrixresize() const max_d1 long = 2 const max_d2 long = 3 dim arr() variant initmatrix arr, max_d1, max_d2 printmatrix "original array:", arr resizematrix arr, max_d1 + 1, max_d2 + 1 printmatrix "resized array:", arr end sub private sub initmatrix(a() variant, n long, m long) dim long, j long dim stringarray() string redim a(n) = 0 n redim stringarray(m) j = 0 m stringarray(j) = * (m + 1) + j next j a(i) = stringarray next end sub private sub printmatrix(heading string, a() variant) dim long, j long dim s string debug.print heading = 0 ubound(a) s = "" j = 0 ubound(a(i)) s = s & a(i)(j) & "; " next j debug.print s next end sub private sub resizematrix(a() variant, n long, m long) dim long dim stringarray() string redim preserve a(n) = 0 n - 1 stringarray = a(i) redim preserve stringarray(m) a(i) = stringarray next redim stringarray(m) a(n) = stringarray end sub
Comments
Post a Comment