C++ Pointers

  1. What are Pointers

    Pointer is variable that stores memory adress of another variable

  2. Creating a Pointer

    To create pointer you use type and * operator

    // creating null pointer
    int* ptr = 0;

    You can get memory adress of variable by using & operator

     int a = 5;
     int* ptr = &a; // ptr holds adress of 'a'

    You get a value of variable that pointer is pointing at by using * operator

     int a = 5;
     int* ptr = &a;
     
     *ptr = 10; // now a is 10
  3. What are References

    A reference is an alias, or an alternate name to an existing variable. You can then manipulate it to change value of referencing variable.
    Reference variable must be set when creating reference.

  4. Creating references

    You can create reference using & operator

    int a = 5;
    int& ref = a; // it stores a reference to a
     
    ref = 2 // a will be set to 2