p!=0 works too. The other methods mentioned by shadowCODE also works (NULL is often defined as 0).
Many of the null and zero checks are unnecessary. Using delete on a null pointer will do nothing and is perfectly safe. Also in the print() function you don't have to check if s is not zero because the loop condition already takes care of that.
When deleting an array you should use delete[].
Your copy constructor and copy assignment operator should use const qualifiers on the parameters (const c& o) so they can be used with temporary objects and variables marked with const:
1 2 3
c var1 = c(); // error because constructor does not accept a const argument
const c var2;
var1 = var2; // error because operator= does not accept a const argument
You also have a problem because p=new int; will allocate one int (not an array) and *p=*(x.p); will assign to that one int. To allocate an array you will have to pass the size inside [ ] like you do in the set function. To copy all values from the other array you should use a loop.
class c
{
int *p;
int s;
public:
c()
{p=0; s=0;}
void set (int v)
{
if (p!=0) delete []p;
s=v;
p=newint [s];
for (int i=0; i<s; i++)
cout<<p[i]<<endl;}
~c()
{delete []p;
} //memory leak problem solved
voidoperator = (const c o[])
{
if (p!=0) delete []p;
p=newint [s];
for (int i=0; i<s; i++)
*p=*(o[i].p); //shallow copy problem solved
}
c (const c x[])
{
p=newint[s];
for (int i=0; i<s; i++)
*p=*(x[i].p);
}
void print ()
{
cout<<s;
if (s!=0)
for (int i=0;i<s; i++)
cout<<p[i]<<endl;
}
};
But I get an assertion error when I put this in the main:
void main ()
{
c o;
o.set(3);
o.print();
c o1;
o1.set(2);
o1.print();
o=o1;
o.print();
o1.print();
}
I've changed it to look like this, but I'm getting an error at *p[i]=*(x.p[i]); saying it must be a pointer,,,
It gave you an error because p[i] and x.p[i] are not pointers, they are the integers at position i in the arrays. Using the deference operator * on an integer doesn't make sense so it gives you an error.
Please someone tell me how to correct these 2 for arrays i am so desperate. I never took Data structures 1. They moved me directly to 2 because apparently i am smart but I dont understand anything
void operator = (const c &o)
{
if (p!=0) delete []p;
p=new int [s];
for (int i=0; i<s; i++)
*p=*(o.p); //shallow copy problem solved
}
c (const c &x)
{
p=new int[s];
for (int i=0; i<s; i++)
*p=*(x.p);
}
E: I just want to know how to place the [] for the loops it isnt working :(