Creating Linked List, not passing back to Main

倾然丶 夕夏残阳落幕 提交于 2019-12-06 13:30:02

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.

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\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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!