创建链表,不传回Main

标签 c pointers linked-list

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

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\n",curr->data);
        curr = curr->next;
    }
    curr = head;
    printf("%d\n",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\n",currOne->data);
    createLL(headTwo,currTwo, ch, number);
    printf("%d\n",currTwo->data);

最佳答案

在 C 函数中按值传递所有参数。因此,如果要更改函数中的变量,则需要传递该变量的地址并取消引用函数中的参数。

此外,您没有为节点分配正确的空间量。您需要 sizeof(struct node),而不是 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\n",(*curr)->data);
        *curr = (*curr)->next;
    }
    *curr = *head;
    printf("%d\n",(*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\n",currOne->data);
    createLL(&headTwo,&currTwo, ch, number);
    printf("%d\n",currTwo->data);
}

关于创建链表,不传回Main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350749/

相关文章:

c++ - 如何解决没有上下文类型信息错误的重载函数?

c - 以下功能的目的是什么?

c++ - fprintf 和 WriteConsole 的输出以相反的顺序发生

c++ - UUID生成器问题

c - makecontext函数指针[错误: invalid use of void expression]

c - C 中的嵌套结构/链表

使用AND按位运算符将十进制转换为二进制的C程序

c - C 中强制转换指针的含义

c - 如何将 FILE* 数组传入函数

python - 单链表删除