The function deletes the desired element from the array by index.

bool del(int *arr, int &length, int index) { if (index < 0 || index > length) return false; for (int i = index; i<length; i++) { arr[i] = arr[i+1]; } length--; return true; } 

Question: let's say there is an array arr [3] = {1,2,3} and you need to delete the element under the index 2 (element equal to 3)

Then the following code will be launched in the function:

 arr[2] = arr[3] 

and what is stored in this arr [3]? The program does not swear at this and adequately removes the index I need, and as a result, the array {1,2} is obtained

    2 answers 2

    It is not known what is stored. Which is generally not recommended to touch.

    You just need to do --length with index == length-1 and that's it.

    Or rewrite the cycle as

     for (int i = index+1; i<length; i++) { arr[i-1] = arr[i]; } 
    • How did you come to this logic? I never in my life would probably have thought of this. What knowledge did you operate on or simple banal experience? - Koki
    • In my opinion, obviously. It is clear that arr [3] is outside. Wrote the first sentence. Next, what are you doing? Shift everything to the left and say that the length is 1 less - i.e. that beyond the length of us, does not wave. Those. the last item will be discarded automatically. So if you delete it - then nothing at all is necessary. So, wrote the second sentence :) I looked at the cycle - we need to move to the last element, but not his. Corrected the cycle, added the answer ... - Harry

    There will be undefined program behavior. Keep in mind that an array that was placed in dynamic memory can be passed to your function, and in this case, when the memory is accessed outside the array, the program can even crash.

    The function has several drawbacks besides addressing beyond the array. She has a complex interface. In addition, indexes are of type int ., Whereas, for example, the sizeof operator returns objects of type size_t . Therefore, it would be better to declare the index and size of the array as having type size_t .

    The function might look like this.

     bool del( int *a, size_t n, size_t i ) { bool success; if ( ( success = i < n ) ) { while ( ++i < n ) a[i-1] = a[i]; } return success; } 

    The function might be called as follows.

     if ( del( arr, length, index ) ) --length; 

    Or, for example

     size_t n = sizeof( arr ) / sizeof( *arr ); n -= del( arr, n, index );