When I run this code the array has a new size after, is there anything wrong or bad about it ?
static int[] ExpandArray(int[] input, int add_size)
{
for (int i = 0; i < add_size; i )
{
int[] temp = input;
input = new int[input.Length 1];
for (var j = 0; j < temp.Length; j )
{
input[j] = temp[j];
}
}
return input;
}
static void Main(string[] args)
{
int[] ovride = new int[3] { 1, 2, 3 };
ovride = ExpandArray(ovride, 10);
ovride = ExpandArray(ovride, 10);
Console.WriteLine(ovride.Length);
}
CodePudding user response:
You can use Array.Resize which:
Changes the number of elements of a one-dimensional array to the specified new size.
int[] ovride = new int[3] { 1, 2, 3 };
Array.Resize(ref ovride, ovride.Length 10);
Array.Resize(ref ovride, ovride.Length 10);
Console.WriteLine(ovride.Length); // prints 23
But if you expect collection size changes List
can be a more suitable option for your goal.
CodePudding user response:
is there anything wrong or bad about it ?
This isn't code review, but:
- Yes. You should not resize arrays. This involves a new allocation and a copy of all elements. As does Array.Resize(), by the way.
- Hey, there is a method that already does this: Array.Resize(). Don't reinvent the wheel.
- You definitely should not do the resize in a loop.
So to clean up the code a little:
static int[] ExpandArray(int[] input, int sizeToAdd)
{
// Create a new array with the desired size
var ouput = new int[input.Length sizeToAdd];
// Copy all elements from input to output
for (int i = 0; i < input.Length; i )
{
output[i] = input[i];
}
// Return the new array, having the remaining
// items set to their default (0 for int)
return output;
}
You'd actually want input
to be updatable by ref
, and then end with input = output
.
Ultimately, just use a List<int>
, as that allows for more efficient resizing, and does so automatically when necessary.