educative.io

Why is this code not working?

int* removeEven(int* &Arr, int size){
	int odd_Count = 0;					
	for(int i = 0; i < size; i++){
		if(Arr[i] % 2 == 0){
			++odd_Count;
		}
	}
	int* tempArr = new int[odd_Count];
	for(int i = 0; i < size; i++){
		if(Arr[i] % 2 == 0){
			tempArr[i] = Arr[i];
		}
	}
	delete [] Arr;
    Arr = tempArr;  	
	return Arr;
}

Hey @darko_lacen! So there are several reasons as to why your code isn’t working. Let us go by them step by step.

First of all, let us look at the following if condition:

if(Arr[i] % 2 == 0){
	++odd_Count;
}

Now, over here, you’re storing the even values rather than the odd values. This would be wrong since we want to remove the even values from our list. Therefore, this would be corrected to the following: if(Arr[i] % 2 != 0).

Moving further into the second loop, we, firstly, again need to correct the if condition. In addition, if you try running the current code, you might be getting a malloc issue. This is because if you notice, your tempArr has a size of only odd_Count and you’re looping over size. Hence, your tempArr is basically iterating over indexes that haven’t been defined so far.

A simple solution to this is keeping track of the indexes of the tempArr array. This can easily be done by creating a new variable and then incrementing that whenever our if condition gets to meet. You can see this below:

int* tempArr = new int[odd_Count];
int j = 0; // New variable created
for(int i = 0; i < size; i++){
	if(Arr[i] % 2 != 0){
		tempArr[j] = Arr[i]; // Incrementing the variable
        j++;
	}
}

The complete solution can be found below:

int* removeEven(int* &Arr, int size){
	int odd_Count = 0;					
	for(int i = 0; i < size; i++){
		if(Arr[i] % 2 != 0){
			++odd_Count;
		}
	}
	int* tempArr = new int[odd_Count];
    int j = 0;
	for(int i = 0; i < size; i++){
		if(Arr[i] % 2 != 0){
			tempArr[j] = Arr[i];
            j++;
		}
	}
	delete [] Arr;
    Arr = tempArr;  	
	return Arr;
}