繁体   English   中英

抛出异常:写访问冲突。 这是 nullptr (C++)

[英]Exception thrown: write access violation. this was nullptr (C++)

我正在尝试初始化一个双链接列表并在其中创建新节点但是,当我尝试创建一个新节点“temp”,用数据填充它,然后将其插入到 dLink 列表中时,我不断收到此错误。 这是代码:

// Node of the Double-Link List
struct node {
    double x, y;
    node *prev;
    node *next;
};
// Double-Link List Function
struct dList {
    node *head;
    node *rear;
};
// Function to check if a list is empty
bool isEmpty(dList *L)
{
    if (L == NULL)
        return true;
    return false;
}
// Function to insert a node at the rear of a list
void insertAtRear(dList *L, double a, double b)
{
    node *temp = new node;
    temp->x = a;
    temp->y = b;
    if (isEmpty(L))
    {
        L->head = temp;
        L->rear = temp;
        return;
    }
    temp->prev = L->rear;
    L->rear->next = NULL;
    L->rear = temp;
    return;
}
// Main Function
int main() {
    dList *L1=NULL;
    dList *L2=NULL;
    string fileName1, fileName2;
    cout << "Please insert the name of the first csv file in which the information is stored:" << endl;
    cin >> fileName1;
    readFile(L1, fileName1);
    cout << "Please insert the name of the second csv file in which the information is stored:" << endl;
    cin >> fileName2;
    readFile(L2, fileName2);
    system("pause");
    return 0;
}

我没有包含 readFile 函数,因为它不是问题,请记住我是从该函数中调用 insertAtRear()

在结构 init 中初始化它们时,我尝试将 *prev 和 *next 设置为 nullptr。 我知道这个问题与指针有关,并且它们没有被正确初始化,但我似乎无法弄清楚如何解决这个问题。

@Yksisarvinen是对的,您是否在readFile函数中初始化了L1L2 它们似乎为空。

“我知道这个问题与指针有关,并且它们没有被正确初始化”

您可以使用类构造函数正确初始化对象

struct node {
  double x, y;
  node *prev;
  node *next;
  node(const double &x, const double &y) : x(x), y(y), prev(nullptr), next(nullptr) {}
  node(const node&) = delete;
 ~node(void) {}
};

struct dList {
  node *head;
  node *rear;
  dList(node *head=nullptr, node *rear=nullptr) : head(head), rear(rear) {}
  dList(const dList&) = delete;
 ~dList(void)
  {
    for (; head != nullptr; head = rear)
    {
      rear = head->next;
      head->next = head->prev = nullptr;
      delete head;
    }
  }
};

isEmpty & insertAtRear应该是这样的:

bool isEmpty(dList *L)
{
  if (L == nullptr) throw "error: null dList pointer!!!!";
  return ((L.head == nullptr) || (L.rear == nullptr));
}

bool insertAtRear(dList *L, double a, double b)
{
  if (L == nullptr) return false;
  node *temp = new node(a, b);
  if (isEmpty(L)) L->head = L->rear = temp;
  else { temp->prev = L->rear; L->rear = L->rear->next = temp; }
  return true;
}

main功能可以是:

int main() {
  dList L1;
  dList L2;
  ...
  readFile(&L1, fileName1);
  ...
  readFile(&L2, fileName2);
  system("pause");
  return 0;
}

我希望这是有帮助的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM