mercredi 27 janvier 2021

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);
}

Aucun commentaire:

Enregistrer un commentaire