-2

I have declared below list:

List<int>[][] main=new List<int>[4][];

main[0]=new List<int>[3];

I am getting error "Object reference not set to an instance of object", if I try to add element using below statement:

main[0][0].add(3);

Can you please let me know what's wrong with the statement and the equivalent correct statement ?

  • 1
    are you trying to create a 3D matrix/array of integers? – Bas Apr 07 '15 at 22:04
  • 2
    Element `0` of `main[0]` is probably still a null List. Instantiate it to a new list first. Please include the actual error (I suspect it's a nullRef exception) – ryanyuyu Apr 07 '15 at 22:05
  • I need array of integers, but size is dynamic – Nagabhushana G M Apr 07 '15 at 22:05
  • 2
    "I am getting error" - *what* error? Is it a compiler error or a runtime error? What's the error message? Please be specific in your questions. – O. R. Mapper Apr 07 '15 at 22:06
  • 2
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) - after reading the basic description, please make sure to read "**Array Elements**" and "**Jagged Arrays**" sections. – quetzalcoatl Apr 07 '15 at 22:12
  • 1
    'I need array of integers, but size is dynamic' that would just look like this; `List`. Based on the comment and the wackiness of `List[][]` I'm not sure if you actually want guidance in using that structure of you're actually looking for something much much simpler like a 2d array or a plain `List`. – evanmcdonnal Apr 07 '15 at 22:13

2 Answers2

5

This instruction main[0]=new List<int>[3];will create an object of type Array of List of size 3 and will allocate the necessary space on the heap for that object but it does not instanciate each element. Each element will have the default value equal to null

Therefore main[0][0].add(3);is an attempt to call add on a null object. You should prior to this line have something like: main[0][0] = new List<int>();

alainlompo
  • 4,130
  • 3
  • 27
  • 39
0

You've left out a step to initiliaze one of the dimensions. The first one is main[0]=new List<int>[3]; but you also need main[0][0] = new List<int>();

So something like this should do it;

        List<int>[][] main = new List<int>[3][];
        main[0] = new List<int>[3];
        main[0][0] = new List<int>();

        main[0][0].Add(1000);

        Console.WriteLine(main[0][0].FirstOrDefault()); // 1000
evanmcdonnal
  • 38,588
  • 13
  • 84
  • 107