创建链表,不传回 Main [英] Creating Linked List, not passing back to Main

查看:31
本文介绍了创建链表,不传回 Main的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在一个单独的函数中创建了一个链表,当我打印出函数内的链表时,似乎一切都很好.然而;当我转到 main 并尝试使用 printf 访问链表时,我遇到了分段错误并且很困惑到底是为什么.

So I am creating a linked list in a separate function, and when I print out the linked list within the function, it seems everything is fine. However; when I go to main and try to access the linked list with printf I get a segmentation fault and am confused exactly why.

void createLL(struct node* head, struct node* curr, char ch, int number){
//lowest digit is the head
    while (((scanf(" %c",&ch)) >= 0)){
        curr = (struct node*)malloc(sizeof(struct node*)); //allocate space
        number = ch - '0' ; //convert char to number
        curr->data = number;
        curr->next = head;
        head = curr;
    }
    curr = head;
    //troubleshoot
    while(curr){
        printf("%d
",curr->data);
        curr = curr->next;
    }
    curr = head;
    printf("%d
",curr->data);
}

int main(){
    //initials
    int i, number; 
    char ch;
    //node pointers
    struct node* headOne = NULL;
    struct node* currOne = NULL;
    struct node* headTwo = NULL;
    struct node* currTwo = NULL;
    //create linked list
    createLL(headOne,currOne, ch, number);
    printf("%d
",currOne->data);
    createLL(headTwo,currTwo, ch, number);
    printf("%d
",currTwo->data);

推荐答案

在 C 函数中按值传递所有参数.所以如果你想改变一个函数中的一个变量,你需要传递那个变量的地址并在函数中解引用这个参数.

In C functions pass all parameters by value. So if you want to change a variable in a function, you need to pass the address of that variable and dereference the parameter in the function.

此外,您没有为节点分配正确的空间量.你想要sizeof(struct node),而不是sizeof(struct node *).

Also, you're not allocating the right amount of space for your node. You want sizeof(struct node), not sizeof(struct node *).

void createLL(struct node **head, struct node **curr, char ch, int number){
//lowest digit is the head
    while (((scanf(" %c",&ch)) >= 0)){
        // don't cast the return value of malloc
        *curr = malloc(sizeof(struct node)); //allocate space
        number = ch - '0' ; //convert char to number
        (*curr)->data = number;
        (*curr)->next = *head;
        *head = *curr;
    }
    *curr = *head;
    //troubleshoot
    while(*curr){
        printf("%d
",(*curr)->data);
        *curr = (*curr)->next;
    }
    *curr = *head;
    printf("%d
",(*curr)->data);
}


int main(){
    //initials
    int i, number; 
    char ch;
    //node pointers
    struct node* headOne = NULL;
    struct node* currOne = NULL;
    struct node* headTwo = NULL;
    struct node* currTwo = NULL;
    //create linked list
    createLL(&headOne,&currOne, ch, number);
    printf("%d
",currOne->data);
    createLL(&headTwo,&currTwo, ch, number);
    printf("%d
",currTwo->data);
}

这篇关于创建链表,不传回 Main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆