Search code examples
clinked-listpass-by-referencefunction-declaration

Is the address of a var in c passed by value?


this how the variable is passed from the main func:

Node merged = NULL; 
ErrorCode result = mergeSortedLists(left, right, &merged);

and this is the signatue of the func.

ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out); 

If an error occurs in func. mergedsortedlists we should return res=Error and the merged list should be NULL

the tutor said we should assign merged_out=NULL; but isn't the address passed by value to the func.? shouldn't we assign the var it points to, to NULL i.e. *merged_out=NULL;

Thanks in advance!


Solution

  • Node merged = NULL; merged is pointer to user defined struct. (its done by typedef operator) for example:

    struct S_Node{
        int m_var;
        struct S_Node* p_m_next;
    };
    typedef struct S_Node* Node;  /*now Node is new type. its pointer to S_Node*/
    

    so merged_out is pointer to pointer. so in case of some error in function, we set it to NULL in this code snippet:

    ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out)
    {
        if(!list1 || !list2) /*lets assume that this is the error case*/
        {
            *merged_out=NULL;
            return Error;
        }
    }