-1

in this C++ function to erase element from array, after erasing it I am getting a garbage value. why is that? and how show resolve it?

void del(int arrDel[], int size)
{
    int temp, pos;
    cout<<"old array is : "<<endl;
    for (int i = 0; i < size; i++)
    {
        cout<<arrDel[i]<<" ";
    }
    cout << "\nenter the position of element to delete : ";
    cin >> pos;
    --pos;
    temp = arrDel[pos];
    for (int i = pos; i < size; i++)
    {
        arrDel[i] = arrDel[i + 1];
    }
    cout<<"element successfully deleted from the array\n";
    
    cout<<"new array is : "<<endl;
    for (int i = 0; i < size; i++)
    {
        cout<<arrDel[i]<<" ";
    }
    
}

OUTPUT ->

old array is : 1 2 3 4 5 enter the position of element to delete : 2 element successfully deleted from the array new array is : 1 3 4 5 6422224

Here I am passing a reference to the array as well as the size of the array in arguments. I am unable to understand why I am getting this 6422224.

output of function

Slick
  • 1
  • 2
  • 1
    `arrDel[i + 1]` is past the end of the array when `i == size-1`. – Eljay May 27 '22 at 15:44
  • https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557 – Marek R May 27 '22 at 15:44
  • 3
    Because you're copying in garbage data at the end of the array? You haven't modified the size of the array, just its content. – Dave Newton May 27 '22 at 15:44
  • I recommend you to enable address sanitizer. https://godbolt.org/z/TzTTK96MM – Marek R May 27 '22 at 15:45
  • thanks for the help, i understand the problem now.☺ – Slick May 27 '22 at 15:47
  • As a matter of terminology, be careful with the word "delete"; you `delete` something you created with `new`. The code here doesn't do that; it **erases** an element from an array. (`erase` is the name used throughout the standard library for code that removes an element) – Pete Becker May 27 '22 at 16:18

0 Answers0