0

I have a structure with some values strucPos [] poss; I need to change it, so I create the same structure structPos[] strpos = poss; and make some changes with it. Then I try to copy strpos to poss, but have an error : object reference not set to an instance of an object.

poss = null;
while (l < strpos.Length)
{
     if (strpos[l].use != "-")
     {
         poss[poss.Length - 1].count = strpos[poss.Length - 1].count;
         poss[poss.Length - 1].ei = strpos[poss.Length - 1].ei;
         poss[poss.Length - 1].id_r = strpos[poss.Length - 1].id_r;
         poss[poss.Length - 1].nm_p = strpos[poss.Length - 1].nm_p;
     }
     l++;
}

As far as I understand it is because poss is null. How should I change my code?

alexander.skibin
  • 133
  • 1
  • 2
  • 15

1 Answers1

2

simple change

poss = null

to

if (strpos.Length > 0)
    poss = new structPos[strpos.Length];

And in the looping, you probably wants to use the "l" instead of "poss.Length - 1".

I would do something like this:

if (strpos.Length > 0)
{
    poss = new structPos[strpos.Length];
    while (l < strpos.Length)
    {
        poss[l] = new structPos();
        poss[l].use = strpos[l].use;

        if (strpos[l].use != "-")
        {
             poss[l].count = strpos[l].count;
             poss[l].ei = strpos[l].ei;
             poss[l].id_r = strpos[l].id_r;
             poss[l].nm_p = strpos[l].nm_p;
        }

        l++;
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Jauch
  • 1,500
  • 9
  • 19