1#include<iostream>
2
3/*
4Pointers: *ptr, point to the memory location of a variable
5int a = 10
6int *ptr = &a //points to the location in memory (0x80ea or whatever)
7instead of the value
8
9in order for pointers to work, the variable it's pointing to needs to
10be de-referenced using &.(If confused, remember that the variable, int a,
11is itself a reference to the location of the value you set it to).
12
13A reference variable: &ref, points to another variable.
14
15int b = 20;
16int &ref = b // points to the value of b, which is 20.
17
18run this if confused:
19*/
20
21 int a = 10;
22 int *ptr = &a;
23 std::cout << "int a value: " << a << std::endl;
24 std::cout << "int ptr value: " << ptr << std::endl;
25
26 int b = 20;
27 int& ref = b;
28 std::cout << "int b value: " << b << std::endl;
29 std::cout << "int ref value: " << ref << std::endl;
30
31 ref = a;
32 std::cout << "int ref after setting it equal to a: " << ref << std::endl;
33 ref = *ptr;
34 std::cout << "int ref after setting it equal to *ptr: " << ref << std::endl;
35 ptr = &ref;
36 std::cout << "ptr after setting it equal to &ref: " << ptr << std::endl;
37 ptr = &b;
38 std::cout << "ptr after setting it equal to &b: " << ptr << std::endl;
39
40/*
41Reference variables CANNOT be set to a pointer variable; In the case above, you
42see we can't just put ref = ptr; ptr HAS to be dereferenced with a *, which in
43turn will give us the value of a, or 10. (dereference pointers with *)
44
45Same goes for pointer variables being set to a reference; you have to dereference
46the reference value (ptr = &b instead of ptr = b;). In the block above, when we
47set ptr = &ref, the ref variable is dereferenced showing us a memory location.
48When ptr=&b is called and we see the output, we noticed it is the same as the previous
49output.
50*/
1Pointers:
2A pointer is a variable that holds memory address of another variable.
3A pointer needs to be dereferenced with * operator to access the
4memory location it points to.
5
6References :
7 A reference variable is an alias, that is,
8another name for an already existing variable.
9 A reference, like a pointer, is also implemented
10by storing the address of an object.