-1

What does this program do? I expected the program to encounter an error why we use new int ? is this correct to delete a ?

#include  <iostream>
#include  <iomanip>
#include  <conio.h>
using namespace std;
#define null NULL 

main()
{
    int x;
    int *a=NULL;
    int *p;
    int c=0,size=0,i;
    while(cin>>x)
    {
        if(c>=size)
        {
            p=new int[size+3];
            for(int i=0;i<size ;++i)
                p[i]=a[i];
            delete []a;      
            a=p;             
            size=size+3;
        }
        a[c++]=x;
    }
}
Stefan Riedel
  • 796
  • 4
  • 15
K .B
  • 1
  • 3
  • 1
    The code copies `a` into `p` then destroys `a` and sets `a` to `p`, this is fairly standard code for growing an array – Alan Birtles Dec 21 '21 at 09:47

1 Answers1

1

The first call to delete []a; is valid, since deleting a nullptr is valid.

So what this program does, is getting user input (cin>>x) and storing it into an array (a[c++]=x;). Every time a is "full" (c>=size), a bigger array is allocated (p=new int[size+3];), contents get copied (for(int i=0;i<size ;++i) p[i]=a[i];) and the old array gets deleted (delete []a;).

But main() {...} is not even valid C++. It should atleast be int main() {...}

That whole program looks like bad C with C++ streams.

PS: #define null NULL in C++? Why not just using nullptr?

PPS: why is using namespace std; considered bad practice

Stefan Riedel
  • 796
  • 4
  • 15
  • @AlanBirtles you're right, my bad – Stefan Riedel Dec 21 '21 at 10:28
  • In a simple example like this, deleting a `nullptr` may be unnecessary, but in more real-world (i.e. non-trivial examples) it is useful and even preferable to alternatives. Even in this example, to avoid deleting a `nullptr` it would be necessary to restructure the code or to do a check (e.g. `if (size > 0) delete [] a`) which is sort of redundant as the standard requires that `delete [] nullptr` has no effect. – Peter Dec 21 '21 at 12:56
  • Hm, I am not sure if the original code has been edited and does not correspond to your answer anymore. You are writing "but unnecessary and IMHO bad style.". But, this is necessary and absolutely correct. This is how we do a dynamic array. Maybe I am looking at the wrong code now . . . You can see a Dynamic Array at the bottom of https://stackoverflow.com/questions/70330230/read-2d-array-from-txt-file-in-c/70332047#70332047 – A M Dec 21 '21 at 15:24
  • @ArminMontigny with "unnecessary and bad style" I just meant deleting nullptr, which could be easily avoided by just not doing it the first time. But I agree with Peter that this is redundant here (`if (a) delete[] a;`) while giving no benefit. I'll just edit my answer, because that statement gives no value to it. – Stefan Riedel Dec 22 '21 at 07:03