0

I want to set values to my struct written en C# and i'm getting one error.

    private struct pack2
   {
      public float var;
      public float [3]var2;
   }
    private struct pack
   {
      public pack2[] ster;
   }

private void recv()
{
     pack mystruct;
     mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
     mystruct.ster[0].var = 2F;
     mystruct.ster[0].var[0] = 1F; // error
} 

ERROR : NullReferenceException was unhandled , Addinfo : object reference not set to an instance of an object

how can I fix it?

SOLVED:

private struct pack2
       {
          public float var;
          public float [3]var2;
       }
        private struct pack
       {
          public pack2[] ster;
       }

    private void recv()
    {
         pack mystruct;
         mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
         mystruct.ster[0].var = 2F;
         mystruct.ster[0].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[1].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[2].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[3].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[0].var2[0] = 1F;
         mystruct.ster[0].var2[1] = 1F;
         mystruct.ster[0].var2[2] = 1F;
    } 

I hope will be useful for people. Thanks to alex

Javi
  • 21
  • 5
  • 4
    Mutable structs are evil. Those should be classes. – SLaks Nov 03 '14 at 03:59
  • I want to echo what SLaks said, and provide this offical guidance from Microsoft: [Choosing Between Class and Struct](http://msdn.microsoft.com/en-us/library/ms229017.aspx) – Troy Gizzi Nov 03 '14 at 04:02

1 Answers1

3

You need to initialize the array.

// One instance
ster = new pack2[1];

You can find more information on Arrays here.

Structs are rarely useful in actual code. Most of the time you should be using classes.

See this answer on when to use structs (rarely).

Community
  • 1
  • 1
Alex Wiese
  • 8,142
  • 6
  • 42
  • 71
  • It works thank u, how I should instance var 2 because i have the same error and i can't instance. thanks – Javi Nov 03 '14 at 04:28
  • The number in the square brackets determines the size of the array during creation. If you want to hold two instances of pack2 then you need to change it to `pack2[2]` etc. – Alex Wiese Nov 03 '14 at 05:08