How this blog work !
" I create this web blog for helping all computer science students and who interested in computer science. That means this blog work as a helper in your educational carrier. If you have any doubts in your subject (computer science) and you want to know more about in your syllabus topics or Seminar topics pleas E-mail your doubts and your name ,college name, Email ID to edugang@gmail.com . Then you will get the answer with in week (I ensure 99% chance to get your answer) in your email address.If you forgot to send your name ,college name ,Email ID then I can’t publish your answer.If you want the answer of any question immediately (with in a day)you can contact me in my number shown in the about "

Wednesday, September 29, 2010

pointer to pointer (c++)

Buzz It
article by www.csedukit.com :


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", it is actually passing a pointer by value. In most cases, this does not present a problem. But, a problem arises when you modify the pointer inside the function. Instead of modifying the variable, you are only modifying a copy of the pointer and the original pointer remains unmodified, that is, it still points to the old variable. The code below demonstrates this behavior.

//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<    //Will still show 2
  return 0;
}
 
void func(int* pInt)
{
  pInt=&g_One;
}

Syntax of Pointer-to-Pointer

This is how you call the function with a ptr-to-ptr parameter:
//function prototype
void func(int** ppInt);
 
int main()
{
  int nvar=2;
  int* pvar=&nvar;
  func(&pvar);
  ....
  return 0;
}
Let us see how to modify the pointer in the function using a ptr-to-ptr parameter
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 summarize what all those differencing statements are:
  • ppInt is the ptr-to-ptr. We will never modify this because if we do, we'll lose our grip on the address of the pointer it is pointing to.
  • *ppInt is the pointed pointer. If we modify this, we are modifying the contents of the pointed pointer, which is an address and in the above example, pvar. In other words, we are effectively modifying what pvar points to.
  • **ppInt is the dereferenced twice variable which is what pvar points to.

0 comments:

Post a Comment

 

CSedukit.com | Headlines

Sponsors

Advertise Now!