Pointers and references

 

References
The & operator is used to create references. References are like alias of a variable. i.e you can refer same variable via the reference variable.

 

Example: 

string subject="Math";     //subject variable
string &study= subject;    //Reference to subject 

Now either 'subject or study can be used to refer to the subject variable. Hence value of it which is maths can be got by any of these two methods.
 

Example:

#include <iostream>
#include <string>
using namespace std;

int main()
{
 string subject= "Math";
 string &study = subject;

 cout << subject << "\n";
 cout << study << "\n";
 return 0;
}


Output:
 


Math
Math



Memory Address

 

When a variable is created in C++, it occupies some memory and hence it is allocated a particular location, where it is stored. & is used to get the memory address of a variable; which is the location of where the variable is stored.

 

Example

 


#include <iostream>
#include <string>

using namespace std;

int main() {
  string food = "Panipuri";
  cout << &food;
  return 0;
}

Output:


0x5dged3

 

Note:The location is in hexadecimal form. The location of storage will vary every time and so the display of output will show different values.

 

Creating Pointers:

 

A pointer is a variable that stores the memory address as its value.

 

The pointer is created using *. It points to an address of the same datatype variable. The address is then assigned to the pointer.

 

Example:

 


#include <iostream>
#include <string>

using namespace std;

int main() {
  string food = "Panipuri"; // A string variable
  string *p = &food; // A pointer variable that stores the address of food

  // Output the value of food
  cout << food << "\n";

  // Output the memory address of food
  cout << &food << "\n";

  // Output the memory address of food with the pointer
  cout << ptr << "\n";

  return 0;
} 

 

Output:

 


Panipuri
0x7def3
0x7def3

 

Note

* Does two different things in the code:

When used in declaration (string* p), it creates a pointer variable and points to an address.

When not used in declaration, it act as a operator which gives the value at a given address.