所以我对编程非常陌生,所以我希望你记住,我很有可能犯了一个非常愚蠢或基本的错误。在尝试用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();
}发布于 2018-08-09 22:41:39
x=x->next;
}
x->next=NULL;您没有为下一个分配任何内存,然后取消了对它的引用。
顺便说一句,你没有在任何地方保存第一个节点,所以在函数调用列表之后,分配的内存就会丢失
发布于 2018-08-09 23:01:31
嗨,我对你的代码做了一点修改。以下是修改后的版本
#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;
}如有任何澄清,请回复。
https://stackoverflow.com/questions/51769812
复制相似问题