Why I can't get an output by declaring a structure variable, but it's all right when using a structure pointer?


  • 0
    C

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {

    struct ListNode* root = (struct ListNode*)malloc(sizeof(struct ListNode));
    
    struct ListNode* p = root;
    int carry = 0;
    int mod;
    while(l1||l2||carry)
    {
        if(l1) 
        {
            carry += l1->val;
            l1 = l1->next;
        }
        if(l2) 
        {
            carry += l2->val;
            l2 = l2->next;
        }
        mod = carry%10;
        carry = carry/10;
    

    // the question is here. In this way, this function return a null pointer, but it works all right with my laptop...

        struct ListNode nNode; 
    
        nNode.val = mod;
        nNode.next = NULL;
        p->next = &nNode;
        p = p->next;
        /*
        // it'll be all right like below
    
        struct ListNode* nNode = (struct ListNode*)malloc(sizeof(struct ListNode));;
        nNode->val = mod;
        nNode->next = NULL;
        p->next = nNode;
        */
    
    
    }
    return root->next;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.