سؤال

I've got two classes: Vector and Particle...

class Vector {
public:
    float x,y;
};

class Particle {
public:
    Vector* coord;
    Particle(Vector* coord)
    {
        this->coord = coord;
    };
};

... and an array declared like this:

Particle* particles [PARTICLES];

This is my main:

int main(int argc, char** argv)
{
    //Write
    int i = 0;
    do{
        particles[i] = new Particle(new Vector());
    }while(
           ++i<PARTICLES
           );
    i = 0;

    //Read
    int j = 0;
    float s = .0f,
    a = .0f;
    Vector vi = *(particles[0]->coord),
    vj = *(particles[0]->coord);
    do{
        do{
            if(i!=j){
                vi = *(particles[i]->coord);
                vj = *(particles[j]->coord); //FIXME
            }
        }while(
               ++j<PARTICLES //For values >1 throws SIGSEGV
               );
    }while(
           ++i<PARTICLES
           );

    return 0;
}

This throws an SIGSEGV whenever PARTICLES is >1. Commenting out that FIXME line makes it work without errors.

Full code here: http://codepad.org/dI2ve5Pc

Why does it fail and is there a way to fix it?

Thank you :)

هل كانت مفيدة؟

المحلول

The loop is written incorrectly. j is not reset before the second iteration of the inner loop. Why don't you code the loops like most people usually do:

for (i = 0; i < PARTICLES; i++) {
    for (j = 0; j < PARTICLES; j++) {
        // ...
    }
}

نصائح أخرى

Remember to reset j to 0 after every iteration of j's loop:

 do{
  do{
   if(i!=j){
    vi = *(particles[i]->coord);
    vj = *(particles[j]->coord); //FIXME
   }
  }while(
   ++j<PARTICLES //For values >1 throws SIGSEGV
  );

  // Reset j here
  j = 0;
  ///////////////

 }while(
  ++i<PARTICLES
 );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top