c++ - Segmentation fault (core dumped) - Access violation reading location x -


i'm writing toy program c++. i'm having quite lot of trouble segmentation fault @ specific line in code. know segmentation fault means tried access memort not given program. code (somewhat) follows(it's big copy paste) :

class car { protected:    int speed;    std::string brand; public:    car (int s, std::string b):speed(s),brand(b) {        std::cout << "new car has been created" << endl;    }    virtual int is_stopped () {       if (speed==0) return 1;       else return 0;    }    virtual void speed_up () {        speed++;    }    car* clone () {       car* tmp(this);       return tmp;    } }; class fast_car : public car { public:    fast_car (int s, std::string b):car(s,b) { }  }; class slow_car : public car { public:    slow_car (int s, std::string b):car(s,b) { } }; class highway {    int number_of_cars;    car **first;           //there derived classes car hence                double pointer public:    highway (int c, int s, std::string b):number_of_cars(c) {       first = new car*[c];       (int i=0;i<c/2;i++)           first[i] = new fast_car (s,b);       (int i=c/2;i<c;i++)           first[i] = new slow_car (s,b);    }    void speed_up () {       int pos;       pos = rand()%number_of_cars;    //give me random number between 0 , number_of_cars;       if (pos!=0) pos--;   //we don't want position -1           first[pos]->speed_up ();       clone_fast (first[pos], (number_of_cars - pos - 1)); //the second argument remaining array "spots" until end of array    }       void clone_fast (car* cur, int rem) {       car* tmp;       (int i=-;i<=rem;i++)           if ((cur+1)->is_stopped ()) {   //exact line segmentation fault             tmp = cur->clone ();             cur++;          }    } }; 

so there is. tried give recreate problem. i'll try solve further questions. appreciated.

the car*s created new, , aren't contiguous; aren't arrays can pointer-arithmetic around with. (car*) + 1 not same (car**)[i + 1] (which more (car**) + 1). want bit more (*(first + 1))->dothing(), not (first[x] + 1)->dothing().

edit: bit more clear, if can't car[x + 1], can't *(car + 1). since cars in clone_fast() object pointers , not arrays, can't car[x + 1], (cur + 1)->is_stopped() wrong.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -