By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,461 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

can we delete objects in an array by using delete in for loop

bajajv
100+
P: 152
Will this work?
Expand|Select|Wrap|Line Numbers
  1. class A {
  2. public:    A()  {}    ~A() {}
  3. };
  4. int main(int argc, char* argv[])
  5. {
  6.         A* x = new A[10];
  7.         for (int i=0; i<10; i++)
  8.         { 
  9.                delete x[i];   //compilation error in this line
  10.         }
  11.         if (x)
  12.                 delete x;
  13. }
  14.  
I am using borland c++ 5.0
on compilation, it gives error E2157 Deleting an object requires exactly one conversion to pointer operator
Aug 8 '07 #1
Share this Question
Share on Google+
3 Replies


gpraghuram
Expert 100+
P: 1,275
Will this work?
class A {
public: A() {} ~A() {}
};
int main(int argc, char* argv[])
{
A* x = new A[10];
for (int i=0; i<10; i++)
{
delete x[i]; //compilation error in this line
}
if (x)
delete x;
}

I am using borland c++ 5.0
on compilation, it gives error E2157 Deleting an object requires exactly one conversion to pointer operator
As the compiler says its an error.
U have to use delete []x to delete it.

Raghuram
Aug 8 '07 #2

Expert 100+
P: 181
Will this work?
class A {
public: A() {} ~A() {}
};
int main(int argc, char* argv[])
{
A* x = new A[10];
for (int i=0; i<10; i++)
{
delete x[i]; //compilation error in this line
}
if (x)
delete x;
}


I am using borland c++ 5.0
on compilation, it gives error E2157 Deleting an object requires exactly one conversion to pointer operator
This error could be solved by using delete &(x[i]). But would result in run time error. You could use delete [] x. I am not able to figure out any other method
Aug 8 '07 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
This code:
A* x = new A[10];
for (int i=0; i<10; i++)
{
delete x[i]; //compilation error in this line
}
will never work.

x is a pointer to and array of 10 A objects. x[i] is one of those objects. You cannot delete an element in an array. You need to delete the entire array.

However, this is C++, ao I ask why you are using arrays in the first place?? You should be using a vector and with a vector you can do exactly this.
Aug 8 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.