0

My code:

Stack<int>[] stk = new Stack<int>[5];
stk[2].Push(54);
stk[1].Push(768);

Error:

System.NullReferenceException: 'Object reference not set to an instance of an object.

The debugger shows that I have 5 stacks initialized to null values. How can I initialize those 5 stacks so I can push values into them?

I also tried:

List<Stack<int>> data = new List<Stack<int>>( );

then created stacks a, b, c, etc and pushed them into data with data.Add(a) etc. and this works fine ( data[1].Push(345) ) but the number stacks I need to store varies and I want to be able to iterate through the stacks or reference them individually.

Or is there a better, hopefully easier, way to do this with arrays maybe?

Itchydon
  • 2,293
  • 5
  • 16
  • 30
  • 1
    `Stack[] stk = new Stack[5];` does not create 5 stacks. It an array of 5 pointers to a stack. You actually need to create each stack too. `stk[0] = new Stack` etc – pm100 Aug 29 '17 at 16:21
  • Exactly what I needed. Works perfectly. As a newbie I read all the information suggested by Jeroen however could not readily see how it applied to what I was doing. Re-reading all of that, your answer helped me see how it did. Thanks. – Edward Warren Aug 29 '17 at 20:12

0 Answers0