Search code examples
c#functionjagged-arrays

c# jagged array changes itself


I've run into a problem. I created a jagged array (input), then I go through some functions and expected to create another jagged array from it (output). But somehow original array was also changed in that process. How can I avoid changes in the original array?

double[][] input;
    double[][] output;
    private void button1_Click(object sender, EventArgs e)
    {
        input = new double[][]
        {
            new double[] {0,1,2,3 },
            new double[] {9,8 },
            new double[] {14,5,0 },
            new double[] {2.0,2.3,2.5 }
        };
        output = function(input);
    }
    static double[][] function (double[][] ins)
    {
        double[][] ous = ins;
        int leng = ins.GetLength(0);
        for (int i = 0; i < leng; i++)
        {
            int lung = ins[i].GetLength(0);
            for (int j = 0; j < lung; j++)
                ous[i][j] += 14.4;
        }
        return ous;
    }

Solution

  • The problem is that ous variable points to the same array as ins (reference). You should copy it to new array. For example using linq:

    static T[][] CopyArray<T>(T[][] source)
    {
        return source.Select(s => s.ToArray()).ToArray();
    }
    

    And use it:

    double[][] ous = CopyArray(ins);