5,699,997 members and growing! (14,216 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Intermediate

Pointer to Pointer and Reference to Pointer

By Wong Shao Voon

Explains the reason behind using pointer-to-pointer and reference-to-pointer to modify a pointer passed to a function.
VC6, VC7, VC7.1, C++, Windows, Visual Studio, Dev

Posted: 31 Aug 2003
Updated: 31 Aug 2003
Views: 134,828
Bookmarked: 33 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
45 votes for this Article.
Popularity: 5.63 Rating: 3.41 out of 5
13 votes, 31.7%
1
4 votes, 9.8%
2
2 votes, 4.9%
3
10 votes, 24.4%
4
12 votes, 29.3%
5

Contents

Introduction
Why We Need Them?
Syntax of Pointer to Pointer and Reference to Pointer
Preference of one over the other?
Do not Mistake Pointer to Pointer arguments
Reference to Pointer type (RTTI)
What Are Other Alternatives?
Conclusion

Introduction

This article explains the reason behind using pointer-to-pointer and reference-to-pointer to modify a pointer passed to a function, so as to better understand their usage. For brevity, I use the terms, ptr-to-ptr and ref-to-ptr to represent them respectively. In this article, I'm not going to discuss how to use ptr-to-ptr as a 2 dimensional array or array of pointers. Please note we can use ptr-to-ptr in C and C++ but we can use ref-to-ptr only in C++.

Why We Need Them?

When we use "pass by pointer" to pass a pointer to a function, only a copy of the pointer is passed to the function. We can say "pass by pointer" is passing a pointer using "pass by value". In most cases, this do not present a problem. But problem comes when you modify the pointer inside the function, instead of modifying the variable it points to by de-referencing, because when you modify the pointer, you are only modifying a copy of the pointer and the original pointer still remains unmodified. The code below demonstrates this behavior.

#include<iostream>


//global variable

int g_One=1;
//function prototype

void func(int* pInt);

int main()
{
  int nvar=2;
  int* pvar=&nvar;
  func(pvar);
  std::cout<<*pvar<<std::endl;//Will still show 2

  return 0;
}

void func(int* pInt)
{
  pInt=&g_One;
}

Syntax of Pointer to Pointer and Reference to Pointer

This is how you called the function with ptr-to-ptr parameter.

//function prototype

void func(int** ppInt);

int main()
{
  int nvar=2;
  int* pvar=&nvar;
  func(&pvar);
  ....
  return 0;
}

Now let us look at how you called the function with ref-to-ptr parameter

//function prototype

void func(int*& rpInt);

int main()
{
  int nvar=2;
  int* pvar=&nvar;
  func(pvar);
  ....
  return 0;
}

In case, you may wonder whether in the above func(), the parameter rpInt should be pointer to reference. Just take my word for it that it is called ref-to-ptr and it is ref-to-ptr.

Let us see how it to modify the ptr-to-ptr in the function.

void func(int** ppInt)
{
  //Modify the pointer, ppInt points to

  *ppInt=&g_One;
  //You can also allocate memory, depending on your requirements

  *ppInt=new int;
  //Modify the variable, ppInt points to

  **ppInt=3;
}

Let me surmarise what all those dereferencing are,

  • ppInt is the ptr-to-ptr, we will never modify this because if we do, we lose our grip on the pointer it is pointing to.

  • *ppInt points to the pointer, if we modify this, we are modifying the contents of this pointer which is an address, In other words, we are effectively modifying the pointer, ppInt points to.

  • **ppInt points to the pointer which in turn points to the variable. So by de-referencing twice, we get the variable.

Let us see how it to modify the ref-to-ptr in the function.

void func(int*& rpInt)
{
  //Modify the pointer, ppInt points to

  rpInt=&g_One;
  //You can also allocate memory, depending on your requirements

  rpInt=new int;
  //Modify the variable, ppInt points to

  *rpInt=3;
}

Let me once again summarize what all those dereferencing are,

  • rpInt is the reference for the pointer

  • *rpInt dereferences the pointer it references, so you get the variable the pointer is pointing to.

Preference of one over the other?

Now we have seen the syntax of ptr-to-ptr and ref-to-ptr. Are there any advantages of one over the other? I am afraid, no. The usage of one of both, for some programmers are just personal preferences. Some who use ref-to-ptr say the syntax is "cleaner" while some who use ptr-to-ptr, say ptr-to-ptr syntax makes it clearer to those reading what you are doing.

Do not Mistake Pointer to Pointer arguments

Do not mistake every ptr-to-ptr arguments as purely ptr-to-ptr. An example would be when some write int main(int argc, char *argv[]) as int main(int argc, char **argv) where **argv is actually an array of pointers. Be sure to check out the library documentation first!

Reference to Pointer type (RTTI)

You cannot use RTTI to find out the type of ref-to-ptr. As typeid() does not support reference types.

void test(int*& rpInt)
{
  std::cout << "type of *&rpInt: " << typeid(rpInt).name() 
    << std::endl;//will show int *

}

What Are Other Alternatives?

If you find that the ptr-to-ptr and ref-to-ptr syntax are rather hard to parse, you can just use the "return the pointer" method.

int* func()
{
  ....
  return new int;
}

Conclusion

You may ask if you would ever use ptr-to-ptr and ref-to-ptr in your projects and if it is necessary to know about them. Well, as developers, we use libraries and technologies developed by others. One example would be COM uses ptr-to-ptr to return an interface pointer using CoCreateInstance() and IUnknown::QueryInterface(). Up to some point in your developer career, you are definitely going to come across them. It is good to know them.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Wong Shao Voon


I am currently working as a software developer in a company specialized in 3D modelling software. My wish is to write a article on GUI since I am specialized in GUI.

Like many Singaporeans, my hobbies include reading, karaoke, watching movies and anime, play games and jogging.

I wish I have more time to write articles for CodeProject since I have a few ideas(long overdue) to write about. And I always explain the working behind the code in my articles. I hope you like my articles on CodeProject!
Occupation: Software Developer
Location: Singapore Singapore

Other popular C / C++ Language articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
GeneralReference to a pointer and typing.memberDavid G Hunt12:48 22 Sep '08  
Generalvery nice article,membermorten414:59 29 Oct '07  
GeneralRe: very nice article,memberWong Shao Voon18:24 29 Oct '07  
GeneralRe: very nice article,membermorten412:14 30 Oct '07  
QuestionThanks for it, but how to get it to work in .NET 2005memberMausOnMars0:30 16 Oct '07  
AnswerRe: Thanks for it, but how to get it to work in .NET 2005memberWong Shao Voon0:40 16 Oct '07  
GeneralRe: Thanks for it, but how to get it to work in .NET 2005memberMausOnMars0:57 16 Oct '07  
GeneralRe: Thanks for it, but how to get it to work in .NET 2005memberWong Shao Voon4:41 16 Oct '07  
Generalc++ questionsussEasyPro16:31 1 Oct '05  
GeneralRe: c++ questionmemberChristian Graus20:32 1 Oct '05  
Generalwrite a program which displays its own source code as out putsussAnonymous12:24 12 Jul '05  
GeneralRe: write a program which displays its own source code as out putmemberChristian Graus15:36 12 Jul '05  
GeneralThankssussAnonymous4:42 26 Mar '05  
GeneralWhen to use ptr-to-ptr and ref-to-ptr?memberCBasicNet16:22 9 Sep '03  
GeneralAlternative suggestionmemberhain5:26 9 Sep '03  
GeneralRe: Alternative suggestionmemberCBasicNet16:17 9 Sep '03  
GeneralReferencesmemberRalph Walden8:14 2 Sep '03  
GeneralRe: ReferencesmemberForogar3:29 4 Sep '03  
GeneralRe: ReferencessupporterBrad Sokol6:02 9 Sep '03  
GeneralRe: Referencesmemberf28:12 11 Oct '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 31 Aug 2003
Editor: Nishant Sivakumar
Copyright 2003 by Wong Shao Voon
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project