Search Tools Links Login

Dynamic Memory Allocation


Read this to learn how to create arrays and resize them at runtime for efficient and unlimited memory storage. You will also learn how to resize arrays based on user input. This is something every vb programmer should know.

Original Author: Justin Tunney

Code

Creating an array:

dim arTemp(5) as integer
-Creates array with 6 storage spaces, 0,1,2,3,4,5. Remember VB starts counting at 0)

dim arTemp(1 to 5) as integer
-Creates another array with 5 value holding places; 1,2,3,4,5.)

Setting up arrays sized by user input

Now this all works good if you want to create an array where you know what it needs to use and wont need anymore or less.

Now lets say you wanted to create a program that takes a given string and splits up each character from the string and puts each one into a different array value holder. You don't know how large the given string will be so your array has to be the same size as the length of the string to hold each character. When you declare arrays you aren't allowed to say:

dim arTemp(len(text1.text))

because vb declares all variables in your procedure before it executes the procedure. The solution is to use the 'ReDim' statement thingy. Heres an example:


dim arTemp() as string

dim sTemp as string

sTemp = inputbox("type it in")

ReDim arTemp(len(sTemp)) as string

' you now have an array with as many value

' holders as characters in the typed in string,

' the rest is up to you.


Resizing arrays during usage


Ok just to be annoying lets say you were creating a chat server. For every person that connects, you will need a variable in which to store their nickname, chatroom they are in, etc. People connect at different times so you will probably need to edit the size of an array you are already using. You tried to do it with 'ReDim' but darn, every time you use 'ReDim' it destroys all data put into your array. Welp son, there is a simple solution to this, heres an example:


Dim arTemp() as string

ReDim arTemp(1 to 2) as string

arTemp(2) = "hi there"

ReDim Preserve arTemp(1 to 3) as string

arTemp(3) = "hi again"

msgbox artemp(2)

msgbox artemp(3)


that code works wonders! hooray. now try taking 'preserve' out of that and run it again. uh oh.

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 85 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.