抛出异常:读取访问冲突。当前是 0xCDCDCDCD

时间:2021-01-29 16:51:48

标签: c++ linked-list singly-linked-list

我正在尝试显示第二个列表。当我运行代码时,第二个列表被打印出来,但编译器抛出一个异常,说“cur was 0xCDCDCDCD”。

我试图让用户输入一个列表,然后编译器用第一个列表的元素的平方创建第二个列表。

这是问题的代码。


/*
Write a program that inputs from the user a simple linked list of integer elements. The
program should create a new list that is the list of the square of the elements of the
previous list. Output the list.
*/
#include <iostream>
#include <cmath>
using namespace std;

struct node {
    int data;
    node* next;
};

node* input(int n) {
    node* cur, * head, * tmp;
    tmp = new node;
    cout << "enter a new node" << endl;
    cin >> tmp->data;
    head = tmp;
    cur = tmp;
    for (int i = 0; i < n - 1;i++) {
        tmp = new node;
        cout << "enter a new node" << endl;
        cin >> tmp->data;
        cur->next = tmp;
        cur = tmp;
    }
    return head;

}



node* square(node* head, int n) {
    node* head1, * cur, * cur1, * tmp;
    cur= head;
    tmp = new node;
    tmp->data = pow(cur->data, 2);
    head1 = tmp;
    cur1 = tmp;
    cur = cur->next;
    for (int i = 0;i < n - 1;i++) {
        tmp = new node;
        tmp->data = pow(cur->data, 2);
        cur1->next = tmp;
        cur1 = tmp;
        cur = cur->next;
    }
    return head1;
}

void displayList2(node* head1) {
    node* cur;
    cur = head1;
    while (cur != NULL) {
        cout << cur->data << " ";
        cur = cur->next;
    }
}

int main() {
    int n;
    cout << "enter number of nodes: ";
    cin >> n;
    node* head, * head1;
    head = input(n);
    head1 = square(head, n);
    displayList2(head1);
}

堆内存或类似的东西有问题吗? 我做错了什么?

0 个答案:

没有答案
相关问题