C++ Pointers and References

Pointers

  • Why pointers
    • Faster array operation
    • Access large blocks of data out of functions
    • Allocate memory space dynamically at runtime
  • Declare and initialize a pointer
    • long* pnumber = NULL;
    • long* pnumber2 = &number2;
  • Assign memory address to a pointer
    • Using the address-of operator (&)
    • pnumber = &number;
  • Obtain value pointed to by a pointer
    • Use de-reference operator (*)
    • *pnumber++;
  • A pointer should ALWAYS be initialized. Otherwise, it might contains random value.
  • Example

      int* pnum1 = NULL;
      int num1 = 10;
      pnum1 = & num1;
      ++*pnum1;
      *pnum1 += 10
      cout << "num1 is now: " << num1 << endl;
      // num1 should be 21
  • Pointers to char
    • char* can be initialized with a string literal
    • char* pproverb = “A miss is as good as a mile”;
      • Ends with \0
      • // Print out the string
      • cout << pprover << endl;

References

  • A reference is an alias for another variable
    • so the variable it’s referencing needs to be declared first
    • a reference can’t be reassigned to another variable
  • Declare and initialize
    • long number = 0;
    • long& rnumber = number; // rnumber is an alias to number now
    • rnumber += 10; // same as number += 10;
  • If we use pointer then
    • long number = 0;
    • long* pnumber = &number; // pnumber stores the address of number variable
    • *pnumber += 10; // pnumber has to be de-referenced
This entry was posted in cpp. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.