3 Replies - 604 Views - Last Post: 05 December 2011 - 05:53 PM Rate Topic: -----

#1 muffintheman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-December 09

How to pass a pointer by reference (in effect)?

Posted 05 December 2011 - 04:32 PM

Hi, I'm wondering how to change the contents of a pointer (not what the pointer points to, but the address that it stores) when I pass it as an argument to a function. Currently, I declare a pointer to a node and store an address in it:
node* head;
node Bobby;
head = &Bobby;


Then, I pass the pointer to a function:
void singleRight(node* root, node* head)
{		
	if(root == head)
	{
		head = holder;
	}
}


But this only changes "head" locally. I feel like this should be pretty simple...what am I missing?

Is This A Good Question/Topic? 0
  • +

Replies To: How to pass a pointer by reference (in effect)?

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2127
  • View blog
  • Posts: 3,260
  • Joined: 21-June 11

Re: How to pass a pointer by reference (in effect)?

Posted 05 December 2011 - 04:45 PM

Well, as your title already suggests, you can solve this by passing the pointer by reference. I.e. just add a & to head's type in the parameter list.

This post has been edited by sepp2k: 05 December 2011 - 04:45 PM

Was This Post Helpful? 1
  • +
  • -

#3 GWatt  Icon User is offline

  • member icon

Reputation: 278
  • View blog
  • Posts: 3,078
  • Joined: 01-December 05

Re: How to pass a pointer by reference (in effect)?

Posted 05 December 2011 - 04:49 PM

In C you would pass a pointer to a pointer. In C++ you could pass a pointer by reference.
void p2p(char **p, int size) {
    *p = malloc(size);
}
int main() {
    void *p;
    p2p(&p);

    free(*p);
}


void r2p(char *&p, int size) {
    p = new char[size];
}
int main () {
    char *p;
    r2p(p, 10);

    delete p;
}


This post has been edited by GWatt: 05 December 2011 - 06:02 PM

Was This Post Helpful? 2
  • +
  • -

#4 muffintheman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-December 09

Re: How to pass a pointer by reference (in effect)?

Posted 05 December 2011 - 05:53 PM

Thanks a bunch! I ended up with this (which worked):

node* head;
node Bobby;
head = &Bobby;

void singleRight(node* root, node *&head)
{
     if(root == head)
     {
          head = whatever;
     }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1