Initializing An Array inline

arct-075 This is part two of the discussion I started yesterday about the StackOverflowException, where I explained how memory gets allocated for the different types of variables we have in our systems and how understanding that can prevent the StackOverflowException.  The question came back with some code this time which looked something like this:

private mystruct[] m_struct =
    new mystruct[6000000];
private mystruct[] GetStructArray()
{
    m_struct[0] =
        new mystruct(3, 2);
    ...
    m_struct[5900000] =
        new mystruct(5,4);
}
struct mystruct
{
    public mystruct(int i,int j)
    {
        m_i = i;
        m_j = j;
    }
    public int m_i;
    public int m_j;
}

Ugh!

So what we are actually doing here is

  • Creating an array of a structure
  • Initializing the array with new structure items inside a method.
  • Running out of stack space.

So the obvious question is, “How do we initialize the structure on the heap instead of the stack?”

Well, we sure can’t do it in a method.  Although breaking this up into several functions might help, it isn’t the best way to go about this.

Instead of even calling the method, we can initialize all of the elements when we create the array of structures using this syntax.

private mystruct[] m_struct =
{ new mystruct(0, 4),
    new mystruct(2, 3),
    new mystruct(5,7), etc...};

This creates the array and initializes all in one line.  And it does it all on the heap that is created when the class is instantiated.

This syntax also works for arrays of integers, strings, or any other type you might need to create an array of.

Related Post

Comments are closed.