By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,634 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

Reference Parameters in C

P: 5
Reference parameter can they be done in C?

As in:

I have struct:
Expand|Select|Wrap|Line Numbers
  1. typedef struct listNode listNode;
  2. struct listNode {
  3.     struct listNode *forLink;
  4.     struct listNode *bacLink;
  5.     struct listNode *firLink;
  6.     char *info;
  7. };
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:
Expand|Select|Wrap|Line Numbers
  1. char *listPop(listNode *_node) {
  2.    char *temp;
  3.    listNode *curLink = _node->firLink;
  5.    while (curLink->forLink) 
  6.       curLink->forLink;
  7.    temp = curLink->info;
  8.    _node = curLink->bacLink; //THE PROBLEM
  10.    return temp;
  11. }
Say I call it by:
Expand|Select|Wrap|Line Numbers
  1.    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?
Mar 21 '07 #1
Share this Question
Share on Google+
1 Reply

P: 1,806
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 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
Expand|Select|Wrap|Line Numbers
  1. tempNode = _node;
  2. _node->bacLink->forLink=NULL;
  3. 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
Expand|Select|Wrap|Line Numbers
  1.  n = listPop(new); //where new is a listNode obviously.
should read
Expand|Select|Wrap|Line Numbers
  1.  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})
Mar 21 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.