[英]Segmentation fault:11 in my code for creating a linked list in C
因此,我对编程非常陌生,所以我希望您记住,我犯了一个非常愚蠢或基本的错误的可能性很大。 尝试在C中创建链接列表时遇到了这个问题。对于输出,在遇到分段错误之前,我可以输入2个元素:11。
#include<stdio.h>
struct node {
int data;
struct node *next;
};
void create(){
int temp1,temp2;
printf("Enter the number of elements\n");
scanf("%d",&temp1);
struct node *x=(struct node*)malloc(temp1*sizeof(struct node*));
for(int i=0;i<temp1;i++){
printf("loop\n");
printf("Enter a value\n");
scanf("%d",&temp2);
x->data=temp2;
printf("text\n");
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 elements\n");
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 value\n");
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;
}
请还原为任何澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.