【问题标题】:How can I assign array in a jagged array?如何在锯齿状数组中分配数组?
【发布时间】:2020-10-04 10:41:48
【问题描述】:

我有 3 组数组,它​​们是:a[i]、b[j]、c[k],我必须将它们分配给一个锯齿状数组,以便我将它们显示到输出。

array[0] = new int[3] { a[i] };
array[1] = new int[2] { b[j] };
array[2] = new int[2] { c[k] ];

for (i = 0; i < array.Length; i++)
{
     Console.Write("First Array: ");
     for (int l = 0; l < array[i].Length; l++)
     {
           Console.Write("\t" + array[i][l]);
     }

     Console.Write("Second Array: ");
     for (int m = 0; m < array[i].Length; m++)
     {
           Console.Write("\t" + array[i][m]);
     }

     Console.Write("Third Array: ");
     for (int n = 0; n < array[i].Length; n++)
     {
           Console.Write("\t" + array[i][n]);
     }

     Console.WriteLine();
}

但我无法让它们工作,它们总是给我一个错误。

【问题讨论】:

  • 你得到什么错误?另外,请出示minimal reproducible example
  • @Sweeper 它说 System.IndexOutOfRangeException: '索引超出了数组的范围。'

标签: c# arrays visual-studio console jagged-arrays


【解决方案1】:

在 Javascript 中类似的事情可以通过-


let a =  [ '1','2','3']
let b =  ['4','5']
let c =  ['6','7']

let array = []
array.push(a)
array.push(b)
array.push(c)
console.log(array)

输出

[ [ '1', '2', '3' ], [ '4', '5' ], [ '6', '7' ] ]

【讨论】:

    【解决方案2】:
    int[] a = new int[] { 1, 2, 3 };
    int[] b = new int[] { 4, 5 };
    int[] c = new int[] { 6, 7, 8, 9 };
    
    int[][] array = new int[][] { a, b, c };
    

    【讨论】:

      【解决方案3】:

      这应该看起来更像:

      // place references to the source arrays into the jagged array
      array[0] = a[i];
      array[1] = b[j];
      array[2] = c[k];
      
      // iterate over the jagged array and output each array that is within
      for (i = 0; i < array.Length; i++)
      {
          Console.Write("Array " + i + ": ");
          for (int j = 0; j < array[i].Length; j++)
          {
              Console.Write("\t" + array[i][j]);
          }
          Console.WriteLine();
      }
      

      请注意,我们只有一个内部 for 循环,它使用外部循环的 i 变量迭代每个内部数组。

      【讨论】:

      • 我试过了,但这不起作用。假设数组 a[i]、b[j] 和 c[k] 都是基于用户 @Idle_Mind 输入的数组
      • 贴出更完整的代码。向我们展示如何创建和填充 a、b 和 c。事实上,我们只能猜测问题可能是什么。
      猜你喜欢
      • 2023-03-15
      • 2015-09-23
      • 2020-04-02
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2012-03-20
      相关资源
      最近更新 更多