为什么会出现错误“引发异常:写访问冲突。p为nullptr。”?

时间:2019-04-23 23:49:50

标签: c

我正在对平台进行编码,当我尝试运行它来为每个节点分配值然后打印时,通过addcard方法时会出现此错误:

exception thrown: write access violation. p was nullptr.

为什么不能与NULL一起使用?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

#define RAND_MAX 51

typedef struct card_s {
    char suit;
    int face;
    struct card_s *next, *previous;
} card;

void addcard(card *p, card **hl, card **hr, int i, char c) {
    card *temp;
    temp = (card *)malloc(sizeof(card)); 
    temp->face = i;
    temp->suit = c;
    if (*hl == NULL) {
        temp->previous = NULL;
        temp->next = NULL;
        *hl = temp;
        *hr = temp;
    } else if (p == NULL) {
        temp->previous = p;
        temp->next = NULL;
        p->next = temp;
        *hr = temp;
    } else {
        temp->next = p->next;
        temp->previous = p;
        p->next = temp;
        temp->next->previous = temp;
    }
}

void delectecard(card *p, card **hl, card **hr) {
    if (p == *hl) {
        *hl = p->next;
    } else {
        p->previous->next = p->next;
    }
    if (p == *hr) {
        *hr = p->previous;
    } else {
        p->next->previous = p->previous;
    }
    free(p);
}

void createdeck(card *p, card **hl, card **hr) {
    int i = 1;
    int j;
    while (i <= 13) {
        j = 1;
        while (j <= 4) {
            if (j == 1)
                addcard(p, hl, hr, i, 'S');
            if (j == 2)
                addcard(p, hl, hr, i, 'H');
            if (j == 3)
                addcard(p, hl, hr, i, 'D');
            if (j == 4)
                addcard(p, hl, hr, i, 'C');
        }
    }
}

void printdeck(card *currentNode) {
    while (currentNode != NULL) {
        printf("Face: %d, Suit: %c\n", currentNode->face, currentNode->suit);
        currentNode = currentNode->next;
    }
}

int main(void) {
    card *headl = NULL, *headr = NULL;
    createdeck(headr, &headl, &headr);
    printdeck(headl);
}

1 个答案:

答案 0 :(得分:1)

在您的函数中addcard();您检查p是否为NULL:

else if (p == NULL) {
    temp->previous = p;
    temp->next = NULL;
    p->next = temp;
    *hr = temp;

然后,您尝试访问该行中的NULL p:

 p->next = temp;

如何访问不存在的内容!那就是空指针异常错误的来源。

也许您想像对temp一样将p初始化为新的card_s结构。使用calloc会将下一个和上一个指向NULL的指针初始化。

p = calloc(1, sizeof(card));

此后,您陷入无限循环,特别是在createdeck函数中。原因是您永远不会递增或递减j或i,因此循环永不中断。

while (i <= 13) {

    j = 1;
    while (j <= 4) {
        if (j == 1)
            addcard(p, hl, hr, i, 'S');
        if (j == 2)
            addcard(p, hl, hr, i, 'H');
        if (j == 3)
            addcard(p, hl, hr, i, 'D');
        if (j == 4)
            addcard(p, hl, hr, i, 'C');
    }
}