我从指针练习视频中编写了这段C
代码,遇到的问题是,在将head作为局部主变量集成到main()
之前声明的全局变量之后,该程序不再进入for循环,我似乎不知道为什么。
有趣的是,我删除了head=NULL
,该循环似乎正在执行。有谁知道将NULL分配给head的问题在哪里?
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
struct Node{
int data;
struct Node* next;
};
struct Node* Insert(struct Node* head, int data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
(*new_node).data = data;
(*new_node).next = head;
head = new_node;
}
void Print(struct Node* head){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp = head;
while(temp!=NULL){
printf("%d", (*temp).data);
temp = (*temp).next;
}
printf("\n");
}
int main(){
struct Node* head = NULL;
int n, i, x;
printf("%s", "How large do you want your array to be?\n");
scanf("%d", &n);
for(i; i<n; i++){
printf("Enter a number:\n");
scanf("%d",&x);
head = Insert(head, x);
Print(head);
}
return 0;
}
答案 0 :(得分:2)
我可以看到您的代码有几个问题:
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp = head;
应该是
struct Node* temp = head;
那么我们有
for(i; i<n; i++)
应该是
for(i=0; i<n; i++)
这可能是导致问题的原因,因为这是未定义的行为。
可能引起麻烦的另一件事是,您没有将return head
作为Insert
中的最终声明。
打开编译器警告可以很容易地发现其中两个。