You are using a version without Ads of this website. Please, consider donating:

### Compiling problem with arrays

Greetings,

I was studying C++ with a certain book until I stumbled upon the following exercise:

"Write a program with a int-array, for example:

 ```const int MAX_AMOUNT = 10; int a[ MAX_AMOUNT ] = { 4, 8, 2, 3, 5, 17, 7, 99, 3, 12};```

Write a function that is able to delete a certain value from an array( as often as that value occurs). De other values of the array have to move and the ending values have to be replaced with zeros.
For example: you have to remove 3 from the array:

 `4, 8, 2, 5, 17, 7, 99, 12, 0, 0`
"(rough translation from Dutch)
This is what I came up with so far:

 ``12345678910111213141516171819202122232425262728293031323334`` ``````#include #include using namespace std; void function( int array[], const int length ); void print( int array[], const int length ); int main(){ const int a_l = 10; int a[ a_l ] = { 12, 42, -79, -95, -10, 34, 63, 95, 34, 1}; print( a, a_l ); functie( a, a_l ); } void function( int array[], const int length ){ for( int i = 0; i < length; i++ ){ for( int j = 0; j < length; j ++ ){ if( array[ j ] == array[ i ] ){ for( int k = j; k < length; k++ ){ array[ k ] = array[ k + 1]; } } } } print( array, lengte ); } void print( int array[], const int length ){ for( int i = 0; i < lengte; i++ ) cout << setw( 5 ) << array[ i ]; }``````

I do realize that some features are still missing, like removing both values from the array( now it only removes 1). But when I run my project it gives me the following error:

 `RUN FAILED (exit value 1, total time: 44ms)`

Just to be clear: I am not asking for help with the exercise, but for help on what makes my code fail.

Any help will be appreciated.

EDIT: Line 20: "i++" was changed to "j++"
Last edited on
Line 23, when k == 9 you try to access array[10] which is out of bounds.

Also, unless I misunderstood what you want to do, the initialization of j on line 20 is wrong.
Aha, I see now! Thank you very much.

I've edited the post and fixed the initialization of j in line 20.
Actually I was referring to the fact that if you initialize j to 0 every time the loop starts, there will be "lenght" occurrences of i == j and therefore of `if(array[i] == array[j])` comparing a value with itself, which is always true and causes the rest of the array to be modified.
Though I'm not sure, it doesn't seem the intended behavior.
Yes, that was indeed something that was wrong with the code. I do not want to be ungrateful, but I will try to make the rest of the exercise by myself.
Topic archived. No new replies allowed.