Adding a 2D array to the list. Found a bug and solution, need your explanation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EARNEST
    New Member
    • Feb 2010
    • 128

    Adding a 2D array to the list. Found a bug and solution, need your explanation

    Working fine:

    Code:
            internal double[] AggregationMethod(List<double[]> listOf_D)
            {
                double[] maxD;
                double[] aggregatedD;
                List<double[]> tempList;
    
                maxD = new double[listOf_D[0].Length];
                
                tempList = new List<double[]>();
    
                for (int i = 0; i < maxD.Length; i++) 
                {
    
                    aggregatedD = new double[listOf_D.Count]; 
    
                    for (int j = 0; j < listOf_D.Count; j++) 
                    {
                        aggregatedD[j] = listOf_D[j][i];
                    }
                    tempList.Add(aggregatedD);
    
                    maxD[i] = aggregatedD.Max();
                }
    
                return maxD;
            }
    Bug, while debugging, I see that after certain point, .ElementAt(0) starts changing while I'm trying to add new elements. What is the reason behind it?

    Code:
            internal double[] AggregationMethod(List<double[]> listOf_D)
            {
                double[] maxD;
                double[] aggregatedD;
                List<double[]> tempList;
    
                maxD = new double[listOf_D[0].Length];
                
                tempList = new List<double[]>();
    
                aggregatedD = new double[listOf_D.Count]; 
                
                for (int i = 0; i < maxD.Length; i++) 
                {
    
    
                    for (int j = 0; j < listOf_D.Count; j++) 
                    {
                        aggregatedD[j] = listOf_D[j][i];
                    }
                    tempList.Add(aggregatedD);
    
                    maxD[i] = aggregatedD.Max();
                }
    
                return maxD;
            }
    Call by ref? or something like that? What are the ways to fix it, apart from re-initializing it?
    Thanks in advance
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    I don't know C# but it seems that when you add the array to the list, it is not adding the values in the list, i.e. it is not instantiating a new array, copying the values, and then adding that new array to the list. Rather, it just adds the pointer to the array to the list. Therefore, unless you instantiate a new array, you are doing all your operations on the same array over and over.

    You may not have to instantiate a new array each time if the list object had a method that allowed you to add a copy of the array. In which case, you are merely moving the instantiation out of your function into another function.

    Comment

    Working...