ConsoleWriteLine增加元素; int array_A = new int3 new int123 new int45 new int6 ; int array_B
上面的代码有逻辑错误。在复制array_A到array_B时,没有为array_B的每个子数组分配内存空间,导致在对array_B进行赋值操作时会引发NullReferenceException异常。正确的代码如下:
Console.WriteLine("增加元素");
int[][] array_A = new int[3][] { new int[]{1,2,3 },
new int[]{4,5},
new int[]{6 },};
int[][] array_B = new int[4][];
for (int i = 0; i < array_A.GetLength(0); i++)
{
array_B[i] = new int[array_A[i].Length];
for (int j = 0; j < array_A[i].Length; j++)
{
array_B[i][j] = array_A[i][j];
}
}
array_A = array_B;
array_A[3] = new int[] { 7 };
for (int i = 0; i < array_A.GetLength(0); i++)
{
for (int j = 0; j < array_A[i].Length; j++)
{
Console.Write(array_A[i][j] + " ");
}
Console.WriteLine("");
}
在复制array_A到array_B时,首先为array_B的每个子数组分配内存空间,然后再进行赋值操作。另外,在为array_A的第四个子数组赋值时,需要先为其分配内存空间
原文地址: http://www.cveoy.top/t/topic/ikKw 著作权归作者所有。请勿转载和采集!