Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c++ - Why I get Read Access Violation when I call if(prim == NULL)

There is my algorithm to create a Polynom, using simple linked list, but i don't know why, when the algorithm enter in AddElement and hit the first if(prim == NULL), i get this error: Exception thrown: read access violation. this was nullptr. I mean i've made a lot of lists like this, but now, i really don't understand why doesn't work at all.

class ElemPolinom {
public:
    int gr;
    double coef;
    ElemPolinom* next;
    ElemPolinom() {
        gr = NULL;
        coef = NULL;
        next = NULL;
    }
};
class ListPolinom {
    ElemPolinom* prim, *ultim;
public:
    ListPolinom() {
        prim = NULL;
        ultim = NULL;
    }
    void AddElem(ElemPolinom* p) {
        ElemPolinom* q = NULL;
        if (prim == NULL) { // when the algorithm comes here, is throwing the error
            prim = p;
            ultim = p;
        } else if (prim->gr < p->gr) {
            p->next = prim;
            prim = p;
        } else {
            q = prim;
            while ((q->next != NULL) && (q->next->gr > p->gr))
                q = q->next;
            if (q->next == NULL) {
                q->next = p;
                ultim = p;
            } else {
                p->next = q->next;
                q->next = p;
            }
        }
    }
    void Create(int n) {
        ElemPolinom* p;
        int gr;
        double coef;
        for (short unsigned int i = 1; i <= n; i++) {
            printf("Gradul elementului %d: ", i); cin >> gr;
            printf("Coeficientul elementului %d: ", i); cin >> coef;
            p = new ElemPolinom;
            p->coef = coef;
            p->gr = gr;
            p->next = NULL;
            AddElem(p);
        }
    }
};
void main() {
    ListPolinom* P1 = NULL;
    P1->Create(4);
}
question from:https://stackoverflow.com/questions/65918684/why-i-get-read-access-violation-when-i-call-ifprim-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...