ghostbody / 15-cpp-learning

15 c++ learning repository of SDCS SYSU
6 stars 3 forks source link

defination of struct #13

Open JohnTargaryen opened 8 years ago

JohnTargaryen commented 8 years ago

Morning +7;

struct person {
    person() {
        for (int i = 0; i < 1000; i++)
        friends[i] = 9999;
        id = idcounter;
        idcounter++;
    }
    bool ifisfriend(int id) {
        for (int i = 0; i < 1000; i++) {
            if (friends[i] == 9999)
            return false;
            if (friends[i] == id)
            return true;
        }
    }
    void makefriend(int id) {
        friends[friendcounter] = id;
        friendcounter++;
    }

    void breakup(int id) {
        for (int i = 0; i < 1000; i++) {
            if (friends[i] == id)
            friends[i] = 9999;
        }
    }

    void setid() {
        id = 9999;
    }

    int getid() {
        return id;
    }
    static int friendcounter;
    int friends[1000];
    int id;
    static int idcounter;
};

My struct defination is above, but the gdb tells me that Segmentation fault occured in the scope below. why is that, could you explain it to me ? THX.

 person mike, jack, lily, carson, sucie;
ghostbody commented 8 years ago

Well, why not step into the line and find you problem?

JohnTargaryen commented 8 years ago

i step in, and then Segmentation fault occures... then the program be kiiled in no time

ghostbody commented 8 years ago

I ran your program, no segment fault is reported.


struct person {
    person() {
        for (int i = 0; i < 1000; i++)
        friends[i] = 9999;
        id = idcounter;
        idcounter++;
    }
    bool ifisfriend(int id) {
        for (int i = 0; i < 1000; i++) {
            if (friends[i] == 9999)
            return false;
            if (friends[i] == id)
            return true;
        }
    }
    void makefriend(int id) {
        friends[friendcounter] = id;
        friendcounter++;
    }

    void breakup(int id) {
        for (int i = 0; i < 1000; i++) {
            if (friends[i] == id)
            friends[i] = 9999;
        }
    }

    void setid() {
        id = 9999;
    }

    int getid() {
        return id;
    }
    static int friendcounter;
    int friends[1000];
    int id;
    static int idcounter;
};

int person::friendcounter = 0;
int person::idcounter = 0;

int main() {
  person mike, jack, lily, carson, sucie;
  return 0;
}