Don't use the code from sundip, it is erroneous.
In your original code, there is a memory leak because you loop again and reallocate the memory for a new array on top of the previous one. Since the destructor of all those Fuzzy objects don't get called, the n value keeps on going up and up. So after the first while-loop iteration, that first for-loop with n as bound will corrupt the memory and cause a crash.
Try this code and it works (I tried it, not that I needed to, really..):
#include <iostream>
using namespace std;
class Fuzzy{
public:
static int n;
Fuzzy () { n++; };
~Fuzzy () { n--; };
int position[48];
int score;
};
int Fuzzy::n = 0;
int main () {
Fuzzy* ent;
for(int iter=0; iter<50; ++iter) {
ent = new Fuzzy[20];
for( int n = 0; n < Fuzzy::n; n++){
for( int i = 0; i < 48; i++ ){
ent[n].position[i] = 24;
}
ent[n].score = 567;
}
cout << Fuzzy::n << endl;
delete[] ent; //delete the array you have.
cout << Fuzzy::n << endl;
};
return 0;
};
The output is 20 0 20 0 20 0 20 0 ... as it should be. If you take out the delete[], it will print 20 20 and it will crash.
mike_2000_17
Posting Virtuoso
2,134 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457