【问题标题】:Why does my code stop running when it comes to pointers?为什么我的代码在涉及指针时停止运行?
【发布时间】:2023-03-25 01:09:01
【问题描述】:

我需要用链表制作一个简单的程序,但我的代码只是停止运行。 下面是代码,第一个是主 .cpp 文件,第二个是定义有问题的函数的标头。代码在分配“new_”指针属性(用箭头标记)时停止。顾名思义,该函数需要从数组中生成一个链表,并返回该链表的头部。 我正在使用 dev c++ 进行编译,他没有抛出任何错误或警告。

<main.cpp>

#include<stdio.h>
#include"LinkedList2.h"

int main(){
    node *head;

    int A[] = {2,8,12,9,7};
    int n = sizeof(A) / sizeof(A[0]);

    head = CreateListFromArray(A, n);

    PrintList(head);

    return 0;
}
<LinkedList2.h>

#include<stdio.h>

typedef struct node_{
    int x;
    struct node_ *next;
}node;


node* CreateListFromArray(int A[], int n){
    node *head = NULL, *tmp = head, *new_;

    for(int i = 0; i < n; i++){
        new_->next = NULL;                 //  <------
        new_->x = A[I];                    //  <------
        tmp->next = new_;
        tmp = tmp->next;
    }
    return head;
}

void PrintList(node *head){
    for(node *tmp = head; tmp != NULL; tmp = tmp->next) printf("%d ", tmp->x);
}

【问题讨论】:

  • new_ 未指向已定义的内存位置。如果没有misbehaviour,您将无法取消对它的引用。与your Rubber Duck讨论您希望它指向的位置。
  • 一个指针指向一个内存位置。但是,创建变量并不会为其创建生存空间。您必须使用 new 来创建您期望它指向的空间。在您完成此操作之前,您无法分配其属性。
  • "为什么我的代码在指针方面停止运行?" - cos 指针很难 :-)

标签: c++ arrays pointers linked-list


【解决方案1】:

你需要为每个新节点分配内存

node* CreateListFromArray(int A[], int n){
    node *head = NULL, *tmp = head;

    for(int i = 0; i < n; i++){
        node *new_ = new node():
        new_->next = NULL;                 //  <------
        new_->x = A[I];                    //  <------
        tmp->next = new_;
        tmp = tmp->next;
    }
    return head;
}

你也没有有效的头指针,我把它留给你整理

注意在 c++ 中你不再需要 typedef。

【讨论】:

  • 它仍然无法正常工作,现在它停在您添加的那一行。我也试过` node *new = new node; ` ,不带括号。我让它通过了,现在问题是` tmp->next = new_; `。不知道为什么。
【解决方案2】:

你还得把A[I]改成A[i],因为我不存在

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2023-03-25
    • 2018-07-05
    相关资源
    最近更新 更多