Reference Parameters in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • darkfire
    New Member
    • Mar 2007
    • 5

    Reference Parameters in C

    Reference parameter can they be done in C?

    As in:

    I have struct:
    Code:
    typedef struct listNode listNode;
    struct listNode {
        struct listNode *forLink;
        struct listNode *bacLink;
        struct listNode *firLink;
        char *info;
    };
    Now I'm trying (trying being the operative word here) to write a Pop() (which obviously has to remove the last Node and return the info of it) function:
    Code:
    char *listPop(listNode *_node) {
       char *temp;
       listNode *curLink = _node->firLink;
       
       while (curLink->forLink) 
          curLink->forLink;
       temp = curLink->info;
       _node = curLink->bacLink; //THE PROBLEM
       
       return temp;
    }
    Say I call it by:
    Code:
       n = listPop(new); //where new is a listNode obviously.
    I know in C++ I would be sending the _node as a reference parameter thus when I change it here 'new' would also change. Here however if you GDB it _node changes but it doesn't affect 'new'. How can I do that?
  • DeMan
    Top Contributor
    • Nov 2006
    • 1799

    #2
    I'll assume you are trying to implement a Stack (given the pop() operation). I'm not entirely sure why you need a reference to firLink, but in a well implemented stack that shouldn't be problem....so We'll ignore that for now.

    The pop should be independent of which Node you pass in (so you shouldn't have to set to firLink)....If this is the lastNode (ie forLink == NULL) then we set
    Code:
    tempNode = _node;
    _node->bacLink->forLink=NULL;
    free(tempNode);
    otherwise, we move along forLink until we are at the last Node and do the same thing.


    The thing here is that you can modify the list, but you can't update the callers pointer (although you could do by passing a pointer to a pointer)
    The point is you can update the data Structure, but not the pointer.....

    As long as the caller keeps some reference to firstNode (maybe instead of each Node referencing it), you can modify this structure quite easily.....


    (I'm also wondering whether
    Code:
     n = listPop(new); //where new is a listNode obviously.
    should read
    Code:
     n = listPop(&new); //where new is a listNode obviously.
    {and good idea to avoid using new, but I know this was just for an example})

    Comment

    Working...