C++:xxx中0x00101890处未处理的异常:0xC0000005:读取位置0xcccccccc的访问冲突

C++ : Unhandled exception at 0x00101890 in xxx: 0xC0000005: Access violation reading location 0xcccccccc

本文关键字:0xC0000005 读取 0xcccccccc 访问冲突 异常 位置 未处理 xxx 0x00101890 C++      更新时间:2023-10-16

我遇到了一个无法调试代码的问题。它不断向我显示未处理的异常。

#include <iostream>
#include <stdlib.h>
#include <ctime>
#define max 10
using namespace std;

struct Node{
    int data;
    Node *next;
};
void initNode(Node *tmpHead, int n){
    tmpHead->data =n;
    tmpHead->next =NULL;
}
void displayNodes(Node *cur) {
    cout <<"Data is";
    while(cur){
        cout<< cur -> data << " ";
        cur = cur->next;
    }
    cout << " *n" <<endl;
}
void addNodes(Node * cur, int n){
    Node *newNode = new Node;
    newNode-> data = n;
    newNode-> next = NULL;
    while( cur -> next){
        cur = cur -> next;
    }
    cur -> next = newNode;
}
int countTotalNodes(Node *cur){
    int count =0;
    while(cur){
        count++;
        cur = cur->next;
    }
    return count;
}


void  main () {
    srand(time(NULL));
    Node* head = new Node;
    int i =0;
    int j= 0;
    initNode ( head, rand() %100); 

    for ( int i = 0; i<max-1; i++)
        addNodes( head, rand() % 100);
    cout << endl;
    cout << "Entered array is: " << endl;
    displayNodes( head); 
    Node* array[max];
    Node* cur= head;
    Node* k;
    for( int j = 0; j<max ; j++) 
    {
        array[i] = cur;
        cur = cur->next;
    }
    for (int i=0; i<max-1; i++) //sorting 
    {
        for(int j=0; j<max-i-1; j++)
        {
            if(array[j]->data > array[j+1]->data)
            {
                k = array[j];
                array[j] = array [j+1];
                array[j+1] = k;
            }
        }
    }
    head = array[0];
    for (int i =0; i<max -1; i++)
        array[i]->next = array[i+1];
    array[max-1]->next = NULL;
    cout <<"Sorted Array is: " <<endl;
    displayNodes( head);

}

我找到了无法运行的部分

if(array[j]->data > array[j+1]->data)

我试着重新键入它,但它仍然给我同样的错误。试了几台不同的电脑,它给了我同样的错误,或者它崩溃了。

您的代码显示:

for( int j = 0; j<max ; j++) 
{
    array[i] = cur;
    cur = cur->next;
}

但是使用i作为数组的索引是没有意义的,因为j是循环变量,所以数组包含随机指针,因为它没有正确初始化。

你应该像我刚才做的那样在调试器中运行你的代码,逐步完成程序并观察它的作用——这会让找到这些东西变得更容易。