ReadLine - 数组索引超出范围

问题描述:

我一直在调试这个程序找到错误,但不能成功。出于某种原因,它正在显示错误 - 数组索引越界在这一行 moves [nCount] .sDirection = sStep [0];我知道,这个论坛不是为了调试,我很抱歉。ReadLine - 数组索引超出范围

 class Program 
{ 
    struct move 
    { 
     public char sDirection; 
     public int steps; 
    } 
    static void Main(string[] args) 
    { 
     int nNumOfInstructions = 0; 
     int nStartX = 0, nStartY = 0; 
     move[] moves = new move[nNumOfInstructions]; 


     nNumOfInstructions=Convert.ToInt32(Console.ReadLine()); 


     string sPosCoOrd = Console.ReadLine(); 
     nStartX = Convert.ToInt32(sPosCoOrd[0]); 

     nStartY = Convert.ToInt32(sPosCoOrd[2]); 

     string sStep = ""; 

     for (int nCount = 0; nCount < nNumOfInstructions; nCount++) 
     { 
      sStep = Console.ReadLine(); 
      int length = sStep.Length; 
      moves[nCount].sDirection = sStep[0]; 
      moves[nCount].steps = Convert.ToInt32(sStep[1]); 


     } 


     Console.ReadLine(); 
    } 
} 

在代码中,所述moves阵列被作为零长度的阵列创建的。对于任何索引,访问该阵列将不可避免地抛出一个数组索引越界

你可能想要做这样说:

class Program 
{ 
    struct move 
    { 
     public char sDirection; 
     public int steps; 
    } 

    static void Main(string[] args) 
    { 
     int nNumOfInstructions = Convert.ToInt32(Console.ReadLine()); 
     move[] moves = new move[nNumOfInstructions]; 

     string sPosCoOrd = Console.ReadLine(); 
     int nStartX = Convert.ToInt32(sPosCoOrd[0]); 
     int nStartY = Convert.ToInt32(sPosCoOrd[2]); 

     string sStep = String.Empty; 

     for (int nCount = 0; nCount < nNumOfInstructions; nCount++) 
     { 
      sStep = Console.ReadLine(); 
      int length = sStep.Length; 
      moves[nCount].sDirection = sStep[0]; 
      moves[nCount].steps = Convert.ToInt32(sStep[1]); 
     } 
    } 
}