【发布时间】: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