what is the output of program

82 views Asked by At
#include<iostream>
using namespace std;

int main()
{
  int *arr ;

   arr = new int[10];
  for(int i=0;i<10;i++)
        arr[i] = i;

    delete arr;
    for(int i=1 ; i<10;i++)
cout<<arr[i];

}

I was expecting a answer "123456789", but the answer was "023456789"

2

There are 2 answers

2
way2fawad On
#include<iostream>
using namespace std;
int main()
{
  int *arr ;
   arr = new int[10];
  for(int i=0;i<10;i++)
        arr[i] = i;

    for(int i=1 ; i<10;i++)
    cout<<arr[i];
    delete [] arr;

}
4
Mikel F On

Two problems here: you are deleting the array before using it, which results in undefined behavior.

Second, you are not using the correct form of delete, which is probably why only the first element is cleared.

The delete needs to be moved to after the print loop, and it needs to be changed to:

delete [] arr;