Read from array write to another causes OutOfBoundsException

[code] // include the tare amount
tareAmount = (calibrationPointNEW - calibrationPointFIRST)

//split the recorded data and save into array as String
tempArray = incomingBuffer.Trim.Split(EndOfLine.Windows)

//read from tempArray, convert rounding to integer, subtract tareAmount,
//write to new array recordedGramsArray as integer:

dim grams as Integer
//read data from tempArray
for i as Integer = 0 to tempArray.Ubound
grams = (val(tempArray(i)))
grams = round(grams-tareAmount)
//write grams to new array
recordedGramsArray(i) = grams
next[/code]

Both arrays have been defined as global in a module. I’m getting the correct expected values from grams and the other variables.
When the code reaches recordedGramsArray(i)=grams (second last line of code), it throws up an OutOfBoundsException.
I’ve mucked around for the last hour including defining the array locally but still get the same error.

I’m stumped.

Redim the second array so it matches the first, first.

redim recordedGramsArray( tempArray.Ubound )
for i ...

Thanks Kem, very much appreciated - that’s done the trick.

I’d like to understand the reason why. Is it because the first array (tempArray) has already been referenced - or somthing to that effect?

Initially an array has no size (unless you initialize it with an upper bound of > -1).

[code]Dim arr() As … // empty, same as
Dim arr(-1) As … // also empty

Dim arr(0) As … // can hold one element
Dim arr(1) As … // can hold two elements
// and so on…[/code]
An array can grow and shrink in two ways:

arr.Append(...) // ubound will increase by 1 arr.Insert(...) // ubound will increase by 1 arr.Remove(...) // ubound will decrease by 1 // or ReDim arr(newUbound)
So in your code your tempArray probably grows by some appends, but recordedGramsArray doesn’t and still has an ubound of -1.

Thanks Eli,

I didn’t use append. I did look that option but it didn’t seem like append was necessary for what I was doing.

One other way an array can shrink:

element = arr.Pop   // ubound will decrease by 1

Actually, the Split command is what gives the first array its size.

Well that does make sense.

Yes, of course.