1

So I have this data structure thing to be rather open ended with the amount of data stored. Data is stored through a series of structures. Here are the structures and the variable I'm using:

Dim CurrentRec As Year

Structure Year
    Dim Months() As Month
End Structure

Structure Month
    Dim Dayz() As Days
    Dim MiscExpend(,) As String
End Structure

Structure Days
    Dim Incomes(,) As String
    Dim Expenditures(,) As String
End Structure

And now I have a little test subroutine to test if it works.

Sub Test()
    ReDim CurrentRec.Months(12).Dayz(31).Incomes(4, 4)
    ReDim CurrentRec.Months(12).Dayz(31).Expenditures(4, 4)
    CurrentRec.Months(5).Dayz(12).Incomes(1, 1) = 5
End Sub

Problem is, this code spits out a System.NullReferenceException error, and I can't for the like of me figure out why. Could anyone help?

Kwigg
  • 13
  • 3

2 Answers2

1

You would need to ReDim each array individually:

ReDim CurrentRec.Months(12)
ReDim CurrentRec.Months(12).Dayz(31)
ReDim CurrentRec.Months(12).Dayz(31).Incomes(4, 4)
ReDim CurrentRec.Months(12).Dayz(31).Expenditures(4, 4)
CurrentRec.Months(5).Dayz(12).Incomes(1, 1) = 5

Currently:

ReDim CurrentRec.Months(12).Dayz(31).Incomes(4, 4)

Attemtps to redim the last member Incomes(,) but at that point Months and Dayz are undimensioned, hence the error.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

You haven't instantiated anything. Dim-ing or ReDim-ing an array doesn't instantiate any of its elements, it just amends its size. All of the elements of the array are still null.

Edit: Gah, what I said above was totally wrong and I've just realised why.

Initialization without Preserve. If you do not specify Preserve, ReDim initializes the elements of the new array by using the default value for their data type.

From the ReDim documentation. The default of a struct is a struct, not null. Structs cannot be null.

Tom W
  • 5,108
  • 4
  • 30
  • 52