I created a 2-dimensional array. I need to change the length of for example the first row:
{ x, y, z, a} // trying to change the length of only this row
{ b, c, d, e}
{ f, g}{ h, i}
I wanted to use: array1[,] = new int[4, 4, 2, 2];
but that always has to change the entire list, not only one of the lists.
Please suggest the simplest solution as Im not a very experienced programmer.
I tried:
array1[,] = new int[4, 4, 2, 2];
CodePudding user response:
If you use a true two-dimensional array, like in your attempt, all rows have the same length. If you use an array of arrays, however, you are free to change any of the rows against a different array.
This is called a "jagged array".
(You still cannot change the length of any existing array, you are always replacing them. You would have to copy the elements from the old one over to the new one if desired.)
Here is a small demonstration program. Note how each row must be initialized with a new
expression. The nested initializers ({{1,2}, {1,2,3}}
) you can use for true 2-dimensional arrays don't work here.
using System;
namespace jagged_array
{
class Program
{
static void printJaggedArr(int[][] ja)
{
Console.WriteLine("{");
foreach (var outer in ja)
{
Console.Write("\t{ ");
foreach (var inner in outer)
{
Console.Write(inner " ");
}
Console.WriteLine("}");
}
Console.WriteLine("}");
}
static void Main(string[] args)
{
int[][] jaggedArr
= new int[][]
{ new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6 }
};
printJaggedArr(jaggedArr);
// replace the first of the "inner" arrays.
// if you want to keep the old values in the first elements
// you can use
jaggedArr[0] = new int[] { 21, 22, 23, 24, 25, 26, 27 };
Console.WriteLine("After changing first 'row' (that is, the first array):");
printJaggedArr(jaggedArr);
}
}
}
It produces the following output:
{
{ 1 2 3 }
{ 4 5 }
{ 6 }
}
After changing first 'row' (that is, the first array):
{
{ 21 22 23 24 25 26 27 }
{ 4 5 }
{ 6 }
}