Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 26th, 2012  |  syntax: None  |  size: 1.20 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. c   pointer reference confusion
  2. struct leaf
  3.     {
  4.         int data;
  5.         leaf *l;
  6.         leaf *r;
  7.     };
  8.     struct leaf *p;
  9.  
  10.  
  11. void tree::findparent(int n,int &found,leaf *&parent)
  12.        
  13. leaf *&parent
  14.        
  15. void tree::findparent(int n,int &found,leaf *&parent)
  16. {
  17.     leaf *q;
  18.     found=NO;
  19.     parent=NULL;
  20.  
  21.     if(p==NULL)
  22.         return;
  23.  
  24.     q=p;
  25.     while(q!=NULL)
  26.     {
  27.         if(q->data==n)
  28.         {
  29.             found=YES;
  30.             return;
  31.         }
  32.         if(q->data>n)
  33.         {
  34.             parent=q;
  35.             q=q->l;
  36.         }
  37.         else
  38.         {
  39.             parent=q;
  40.             q=q->r;
  41.         }
  42.     }
  43. }
  44.        
  45. parent=q;
  46.        
  47. void passPointer(int *variable)
  48. {
  49.     *variable = (*variable)*2;
  50.     variable = NULL; // THIS CHANGES THE LOCAL COPY NOT THE ACTUAL POINTER
  51. }
  52. void passPointerReference(int* &variable)
  53. {
  54.     *variable = (*variable)*3;
  55.     variable = NULL; // THIS CHANGES THE ACTUAL POINTER!!!!
  56. }
  57. int main()
  58. {    
  59.     int *pointer;
  60.     pointer = new int;
  61.     *pointer = 5;
  62.     passPointer(pointer);
  63.     cout << *pointer; // PRINTS 10
  64.     passPointerReference(pointer);
  65.     cout << *pointer; // GIVES ERROR BECAUSE VALUE OF pointer IS NOW 0.
  66.     // The constant NULL is actually the number 0.
  67. }