C# Byte array index was outside the bounds of the array - c#

Dear developers why i get error? (index was outside the bounds of the array)

Note that you create MagicList as an array of 450, but in the debugger, it says it's an array of 300. This is because the array you explicitly create is never actually used. It's immediately replaced by the array returned by GetAsBinary. That array is only 300 bytes long, and that's why your code fails. Your loop exit condition must take the actual array size into account, instead of assuming the size. The following code shows a way you could avoid the problem.
byte[] magicList = DBLite.dbMu.GetAsBinary("magicList");
DBLite.dbMu.Close();
for (int i = 0; i < magicList.Length/3; i++) {

Related

In C#, Procedure that modifies incoming array by reversing it?

I've been trying to find a solution to this problem in particular.
Write a procedure that modifies the incoming array of ints by reversing it. Because this is a procedure, it will not return anything. Instead, I will have to modify the array directly, and because arrays are reference type variables, the array will be permanently changed even after this procedure. To reverse an array, imagine the array with an imaginary line in the middle of it, and then swap the numbers on the left with the numbers on the right side.
At the moment, this is the only code I've written down for the problem. Based on the code I've written so far, I don't think I'm approaching it towards the correct solution for it.
public void Test10(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
}
You could use built-in Array.Reverse method, which reverses the sequence of the elements in the entire one-dimensional Array.
Array.Reverse(array); // reverse supplied array
Please note, System.Array.Reverse() does in place transformation.
There are 2 options based on your preference and need
int[] array = {1,3};
Array.Reverse(array);
This will reverse the original array
int[] array = {1,3};
var reversedArray = array.Reverse().ToArray();
This will use linq and new reversed array will be returned and original array will remain as it is

Does the length of a newly instantiated array resolve to 0 or null?

HOMEWORK: I'm getting and index out-of-bounds on the following code. It's a hangman game, and I'm keeping track of the letters I've guessed in a char array.
Here's the assumptions I made:
In the calling method, I have an unpopulated array (char[] displayGuesses = new char[26];) passing to the method below as the char[] usedLetters parameter.
The first iteration of the letter-guessing, the array will be empty.
It's length will be 0.
I populate usedLetters[0] with the letterGuessed parameter.
The next time I guess, length of the array will be 1, so usedLetters[1] gets populated...and so on.
public char[] trackUsedLetters(char letterGuessed, char[] usedLetters)
{
int letterIndex = usedLetters.Length;
usedLetters[letterIndex] = letterGuessed;
return usedLetters;
}
There's a couple things I think may be going on.
When I try to get the length of usedLetters on the first run, the empty array does
NOT return zero, but null. Boom. Out-of-bounds.
There's some issue with passing a blank array defined with 26
members...? But I'm not sure what that issue would even BE, so I have no idea what to google that will yield relevant results.
I may have a scope issue; I found this link to a similar
question for Java, though using a for loop. I don't quite get
what the Java user was going for, but some of the problems sounded
familiar.
I need a second pair of eyes to look at this and point me in the right direction for solving this.
According to the c# specification: (emphasis mine)
1.8 Arrays
Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance. Actual array instances are created dynamically at run-time using the new operator. The new operation specifies the length of the new array instance, which is then fixed for the lifetime of the instance. The indices of the elements of an array range from 0 to Length - 1. The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.
Default Values which gives the char data type default as '\0'
It looks like you want List<char> that can grow (with Add) method.
Arrays have fixed size and following code (that you have in sample) will always throw out of range exception because you are accessing element past last element in array.
usedLetters[usedLetters.Length] = 'c';
More details on array length:
// newArray - array of 0 chars. newArray.Length is 0
var newArray = new char[0];
// nullArray not created, nullArray.Length will throw NullReferenceExcetption
char[] nullArray = null;
// defaultArray = array of 26 characters, each value 0.
// defaultArray.Length is 26;
char[] defaultArray = new char[26];
When you define a new array, but don't manually initialize the items inside of it, it will automatically be initialized with the default values for whatever type the array contains. In your case, you're creating a character array. The default value for a char is '\0', or the null character.
This means that the array is never truly "empty." If you define an array with 26 slots, it will always have that length, unless you make a new array.

How to get number of elements in an array, Extension Method Count() and Length gives the size of Array.

Hi I was trying to find the number of elements in an array
byte[] salt = new byte[32];
now I only have mentioned size 32 so the Length Property of Array and Enumerable's Count Method will give me 32.
Even if I will iterate on this Array salt using for or foreach or any other looping construct it will iterate 32 times and on each index the value is 0 (i.e default value of byte)
Now suppose I do:
for (int i = 0; i < 5 ; i++)
{
salt[i] = 4-i;
}
And I want to know how many elements are inserted sequentially in Array starting from index 0, Here you may say are you fool you iterating it 5 times and you know the number is 5 , but I am having heavy looping and other logic (appending prepending to another arrays of byte) in it. *My question Is there any other inbuilt function that could give me this number 5 ? * Even if I iterate and check for first default value and break the loop there and get the count but there might be the chance last value inserted is 0 like above salt[4] is 0 so that iterating will give me the count 4 which is incorrect . If I am not wrong I think when we declare Array with size like 32 above 32 consecutive memory bytes are reserved and you are free to insert at any index from 0-31 and its your responsibility to keep the track where and how and how many elements are assigned to Array .I hope you got my point And thanks in advance for help.
An array is an array, and in .NET is initialized when it is allocated. Once it's initialized, the question of whether a given value is uninitialized or simply 0 isn't something that's possible to check. A 0 is a 0.
However, you can bypass that in several ways. You can use a List<int>, like #SLaks suggested, to have a dynamically allocated list that's only initialized with the elements you want.
You can also use, instead of an array of int, and array of int?, so a null value isn't the same as a 0.
Short answer is you can't, the array contains 32 integers, .net framework doesn't care if some of them are 0, so you can create your own function that counts how many integers from an array are different than 0, or keep a "count" when you assign values for array elements or something like that.
Or you can use another container, example a list and dynamically add or remove integers from it.
Ok, when you define an array as int[] myArray = int[32]; you are saying, I HAVE 32 ints. Not, create me space for 32 ints that I will fill in later. That's why count is giving you 32.
If you want something which you can genuinly add to and resize, you need to use a List (or one of it's relatives.
If you want to have a "cap" for a list, I found this :Maximum capacity collection in c#

What is the maximum size of an array while using Array.sort() method?

in my application I have an array with 5000 elements. I have to sort these elements.But I am getting error of "Array index Out Of Bound Exception".
Can anybody tell me what can be the maximum size for the array to sort?
Should I use ArrayList ??
There is no specific limit - you are only constrained by memory here, and at this point the array already exists, so this isn't a limitation of Array.Sort. For example:
int[] arr = new int[500000];
Random rand = new Random();
for (int i = 0; i < arr.Length; i++) arr[i] = rand.Next();
Array.Sort(arr); // works just fine
I suspect you might (for example) have an IComparable[<T>] implementation that is throwing an error internally? Or alternatively, perhaps this error has nothing at all to do with Array.Sort, and you have simply considered the wrong line as the cause.
The exception's .StackTrace should reveal everything, of course.
And no: you shouldn't use ArrayList here. Or pretty much anywhere else.

Efficiently shrinking a two dimensional array in C#

What is an efficient way to shrink a two dimensional array to a smaller size in C#?
For example:
var bigArray = new object[100, 100];
var smallArray = new object[10, 10];
bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;
startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;
smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
How will you write SomeShrinkingMethod() ?
Thanks!
EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.
Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?
Yes the best method is almost certainly to loop over each cell, although it might be possible to copy a sequence of each 'row'. The method would need to know lower indices of the square to be copied from the source square, and the size (which might be implicit in the destination square definition).

Categories