簡體   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