Guest User

Pointers and references

a guest
Sep 17th, 2012
40
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cstdio>
  2. #include <new>
  3.  
  4. //typedef demo
  5. typedef int *pint;
  6.  
  7. //typedef pint apint[]; OR
  8. typedef int *apint[];
  9.  
  10.  
  11.  
  12. int main() {
  13.   //Const and cast
  14.   {
  15.     const int *cpi = new int[10];
  16.  
  17.     int *pi = (int*)cpi;
  18.  
  19.     //cpi[0] = 10; //Error;
  20.     pi[0] = 10;
  21.     printf("%d\n", cpi[0]);
  22.     delete[] cpi;
  23.   }
  24.  
  25.   // Jagged array
  26.   {
  27.     apint a = {new int[10], new int[11]};
  28.  
  29.     a[0][0]; //to
  30.     a[0][9];
  31.  
  32.     a[1][0]; //to
  33.     a[1][10];
  34.  
  35.     for (int i = 0; i < 2; ++i)
  36.       delete[] a[i];
  37.   }
  38.  
  39.   //Null pointer
  40.   {
  41.     int *p1 = nullptr; //OR
  42.     int *p2 = 0; //OR
  43.     int *p3 = NULL; //OR
  44.   }
  45.  
  46.   // Reference pointer
  47.   {
  48.     int i = 10;
  49.     int &li = i;
  50.  
  51.     ++li;
  52.     printf("%d\n", i);
  53.   }
  54.  
  55.   // Anti-example with pointers
  56.   {
  57.     int *pi;
  58.     {
  59.       int i = 42;
  60.       pi = &i;
  61.     }
  62.    
  63.     int &li = *pi; //Link to ???
  64.    
  65.     ++li;
  66.     printf("%d\n", li); //May be 43, but may be not...
  67.     //printf("%d\n", i); //Just error
  68.   }
  69.  
  70.  
  71.  
  72.   return 0;
  73. }
RAW Paste Data