Click here to Skip to main content
15,915,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have been trying to use a double array for a simple iteration, however, I seem to have trouble setting values to particular indices. Below, is the code I used. I am getting index out of range exception at the highlighted LOC.

C#
byte[] utf8Bytes = Encoding.Convert(unicode,
                                                utf8,
                                                unicodeBytes);

           
           int k = 1;
         
           int[,] d = new int[k, 3];
           int i = 0;
           int flag = 0;
           foreach (byte b in utf8Bytes)
           {
              
               
               d[k, i] = Convert.ToInt32(b);
               i++;
               if (k < 3)
               {
                   k++;
                   continue;
               }

              

              
           }



what is it that I am doing wrong?
Posted
Updated 8-Aug-15 22:04pm
v5
Comments
Shivangi_K 9-Aug-15 3:32am    
sorry I forgot to highlight, d[k,i]=convert.ToInt32(b) line
Patrice T 9-Aug-15 4:01am    
Highlight broken

Look at your code, and pay attention to every use of k:
C#
int k = 1;

int[,] d = new int[k, 3];
    d[k, i] = Convert.ToInt32(b);
    if (k < 3)
        k++;

So you start with k = 1, allocate an array with one row by three columns...and then try to access the second row...
C# array indices are zero based: so the array you declared had three elements at [0, 0], [0, 1], and [0, 2]
 
Share this answer
 
Quote:
index out of range exception
This error message tells you that you try to use your array with an index out of range.

This is the typical kind of problem easily solved by using a debugger.

- set a breakpoint on the offending line
- run your program in debugger mode
- check the value of variables used to access your array, and compare against the size of your array.
- soon, a bell should start to ring in your mind.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900