首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分段错误:在我用C++创建链表的代码中:11

分段错误:在我用C++创建链表的代码中:11
EN

Stack Overflow用户
提问于 2018-08-09 22:37:00
回答 2查看 66关注 0票数 1

所以我对编程非常陌生,所以我希望你记住,我很有可能犯了一个非常愚蠢或基本的错误。在尝试用C语言创建链表时,我遇到了这个问题。对于输出,我可以输入2个元素,然后就会出现分段错误:11。

代码语言:javascript
复制
#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();
}
EN

回答 2

Stack Overflow用户

发布于 2018-08-09 22:41:39

代码语言:javascript
复制
        x=x->next;
    }
x->next=NULL;

您没有为下一个分配任何内存,然后取消了对它的引用。

顺便说一句,你没有在任何地方保存第一个节点,所以在函数调用列表之后,分配的内存就会丢失

票数 2
EN

Stack Overflow用户

发布于 2018-08-09 23:01:31

嗨,我对你的代码做了一点修改。以下是修改后的版本

代码语言:javascript
复制
#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;
}

如有任何澄清,请回复。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51769812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档