所以我对编程很陌生,所以我希望你记住,我很有可能犯了一个非常愚蠢或基本的错误。我在尝试用 C 语言创建链表时遇到了这个问题。对于输出,我可以在得到分割错误之前输入 2 个元素:11。
#include<stdio.h>
struct node {
int data;
struct node *next;
};
void create(){
int temp1,temp2;
printf("Enter the number of elementsn");
scanf("%d",&temp1);
struct node *x=(struct node*)malloc(temp1*sizeof(struct node*));
for(int i=0;i<temp1;i++){
printf("loopn");
printf("Enter a valuen");
scanf("%d",&temp2);
x->data=temp2;
printf("textn");
x=x->next;
}
x->next=NULL;
}
int main(){
create();
}
x=x->next;
}
x->next=NULL;
您尚未为下一个分配任何内存,然后取消引用它。
顺便说一句,您不会将第一个节点保存在任何地方,因此在函数调用列表和分配的内存丢失
后嗨,我稍微修改了一下你的代码。以下是修改后的版本
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void print(struct node *head) {
while(head){
printf("%d->", head->data);
head = head->next;
}
printf("n");
}
void free_mem(struct node *head) {
struct node *temp;
while(head){
temp = head;
head = head->next;
free(temp);
}
}
//Insertion at the end
struct node *create(struct node *head){
int temp1,temp2;
struct node *temp_node;
printf("Enter the number of elementsn");
if(scanf("%d",&temp1) < 1){
printf("scanf for temp1 failed!n");
exit(1);
}
for(int i=0;i<temp1;i++){
struct node *x;
if(! (x = (struct node*)malloc(sizeof(struct node)))){
printf("malloc of new node failed!n");
exit(1);
}
printf("Enter a valuen");
if(scanf("%d",&temp2) < 1){
printf("scanf for temp2 failed!n");
exit(1);
}
x->data=temp2;
x->next = NULL;
if(!head){
head = x;
head->next = NULL;
continue;
}
//Moving to end
temp_node = head;
while(temp_node->next){
temp_node = temp_node->next;
}
temp_node->next = x;
}
return head;
}
int main() {
struct node *head = NULL;
head = create(head);
print(head);
//freeing dynamically allocated memory
free_mem(head);
return 0;
}
请回复以获取任何澄清。