简体   繁体   中英

C# Array of List Index out of bounds

I've made a program that extracts some info from a file , do some operations with it and store it back on a list. Following this link: Are 2 dimensional Lists possible in c#? I've been able to create a class with a list who would suit my needs. But after some debugging i've found that i was overwriting the list on each loop iteration. Then i decided to make an array of lists - followed this link: How to create an array of List<int> in C#?

Created an array of lists, initialized it and added elements. But when it needs to move to the next list position , it throws the out of boundaries exception.

I've tried a few things (readed about race condition) but none of 'em worked. The problem will happen only when i open more than one file with my code ; otherwise it works perfectly.

Exception is thrown at xmldata , in the last iteration of the current file. Ex: Selected two files, each one will add five elements. In the last element of the first file the exception will be thrown and there's data in the last element's position to be added.

Additional information: Index was outside the bounds of the array. (Exception thrown).

Any help will be appreciated. Thanks a lot.

Code:

List<xmldata>[] finalcontent = new List<xmldata>[9999];
 finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename

                            foreach (Match m in matches)
                            {

                                Double[] numbers;
                                string aux;
                                aux = m.Groups[1].ToString();
                                aux = Regex.Replace(aux, @"\s+", "|");
                                string[] numbers_str = aux.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                                numbers = new Double[numbers_str.Length];
                                for (int j = 0; j < numbers.Length; j++)
                                {
                                    numbers[j] = Double.Parse(numbers_str[j], CultureInfo.InvariantCulture);
                                    //Converts each number on the string to a Double number, store it in a position
                                    //in the Double array
                                    numbers[j] = numbers[j] / 100; //Needed calculus
                                    numbers[j] = Math.Round(numbers[j], 3); //Storing numbers rounded
                                }
                                string values = String.Join(" ", numbers.Select(f => f.ToString()));

                                if (i <= colors_str.Length)
                                {
                                    finalcontent[listpos].Add(new xmldata//The exception is thrown right here
                                    {
                                        colorname = colors_str[i],
                                        colorvalues = values,

                                    });//Closing list add declaration
                                 }//Closing if
                                i++;
                            }//Closing foreach loop

Link to the file: https://drive.google.com/file/d/0BwU9_GrFRYrTT0ZTS2dRMUhIWms/view?usp=sharing

Arrays are fixed size, but Lists automatically resize as new items are added.

So instead, and since you're using Lists anyway, why not use a list of lists?

List<List<int>> ListOfListsOfInt = new List<List<int>>();

Then, if you really absolutely must have an array, then you can get one like this:

ListOfListsOfString.ToArray();
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';

This is a big example, but check this one. You increase 'jx' before entering the statement, possibly exceeding the boundary of cnt?

When using a list - it is better to use native functions for it.

List<xmldata>[] finalcontent = new List<xmldata>(); 
......
 finalcontent[listpos] = new List<xmldata>(); insted of   var _tmpVariable = new List<xmldata>();//Initializing a list for each filename
......
 _tmpVariable.Add(new xmldata
                                    {
                                        colorname = colors_str[i],
                                        colorvalues = values,

                                    });//Closing list add declaration

                    fs.Close();//closing current file
                    listpos++;//Increment list position counter
                    finalcontent.Add(_tmpVariable); // add list into list

As there is no exception details it is hard to get where the exception is thrown. It could be a list issue, a string issue or other (even file reading issue as well), So please update this with current exception details.

Try changing the following:

if (i <= colors_str.Length) 

to

if (i < colors_str.Length). 

In fact I'm convinced that this is the problem.

This is because refereces begin at 0 and the last reference is length - 1, not length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM