Reputation: 28771
This is with regard to previous question posted a while ago Remove -1 entry from integer array
I know there are blazing fast solutions , one line answers as posted in answer section to previous posted question , but being a newbie I tried doing by for loops.
int[] arr = new int[]{ 1, -1, -1, 1 };
int[] new_arr;
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
// Console.WriteLine(arr[i]);
if (arr[i] == -1)
continue;
else
new_arr[index++] = arr[i];
}
I am getting error
Use of unassigned local variable 'new_arr'
what am I doing wrong.
EDIT
int[] arr = new int[]{ 1, -1, -1, 1 };
int[] new_arr = new[arr.Length]; //Error being shown at this line
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == -1)
continue;
else
new_arr[index++] = arr[i];
}
for(int j=0;j<new_arr.Length;j++)
Console.WriteLine(new_arr[j]);
Upvotes: 0
Views: 5122
Reputation: 1039368
The compiler is warning that you haven't initialized the new_arr
variable and you cannot use it later:
int[] new_arr = new int[arr.Length];
In this case I am initializing the new_arr
array to the same size as the arr
array.
Upvotes: 5
Reputation: 188
you haven't assigned your variable new_arr. Therefore it is showing error. Your code can be like this-
int[] arr = new int[] { 1, -1, -1, 1 };
int[] new_arr = new int[4];
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
// Console.WriteLine(arr[i]);
if (arr[i] == -1)
continue;
else
new_arr[index++] = arr[i];
}
for (int i = 0; i < new_arr.Length; i++)
{
Console.WriteLine(new_arr[i]);
}
You can't use any un-assigned or dangling variable in c#. Do not assign new_arr to null. It will throw null reference exception.
Upvotes: 1
Reputation: 223372
You haven't initialized your array new_arry
. You need to specify its size.
int[] new_arr = new int[10];
Inside your code you are doing:
new_arr[index++] = arr[i];
Here since the array has not been initialized and you are trying to use it, that is why you are getting this error.
You may use List<int>
instead of the array, because it seems you are not sure about the Size of the array in your code.
So your code would be:
int[] arr = new int[]{ 1, -1, -1, 1 };
List<int> tempList = new List<int>();
int[] new_arr;
int index = 0;
for (int i = 0; i < arr.Length; i++)
{
// Console.WriteLine(arr[i]);
if (arr[i] == -1)
continue;
else
tempList.Add(arr[i]);
}
new_arr = tmepList.ToArray();
Or the complete code can be shorten to:
int new_arr = arr.Where(r=> r!= -1).ToArray();
Upvotes: 3