Pointers in C++ | Topic 15 | VU Insider



Pointers are special type of variables in which a memory address is stored. They contain memory address instead of value of a variable. A pointer however, is a variable that stores the memory address as its value.

How to know a Memory Address?

In C++ language, we can get the memory address of a variable by using the & operator.

Let's see an example...

Example:

string car = "Honda";
// Outputs the value of car (Honda)
cout << car << "\n";

// Outputs the memory address of car (0x6dfed4)
cout << &car << "\n";code-box


How to create a Pointer?

A pointer variable points to a data type of the same type i.e. int & string. A Pointer is created with the * operator.

Syntax:
data-type* name;code-box

Important Note: There are three ways to declare pointer variables, but the first way is preferred:
string* myprogram; // Preferred
string *myprogram;
string * myprogram;code-box


Example:
string car = "Honda";
// A pointer variable with the name ptr, that stores the address of car
string* ptr = &car;

// Output the value of car (Honda)
cout << car << "\n";

// Output the memory address of car (0x6dfed4)
cout << &car << "\n";

// Output the memory address of car with the pointer (0x6dfed4) cout << ptr << "\n";code-box


Pointers Referencing & Dereferencing:

In the previous example, we used the pointer variable to get the memory address of a variable. However, you can also use the pointer to get the value of the variable by using the * operator. It is known as dereferencing of a pointer.

Example:
string car = "Honda";
string* ptr = &car; // Pointer Declaration

// Output the memory address of car with the pointer (0x6dfed4). It's known as Referencing.
cout << ptr << "\n";

// Output the value of car with the pointer (Honda). It's known as Dereferencing.
cout << *ptr << "\n";code-box


Can we change/modify pointer's value?

Yes, we can change the pointer's value also. But it should be noted that this will also change the value of the original variable.

Let's see an example to better understand.

Example:
string car = "Honda";
string* ptr = &car;

// Output the value of car (Honda)
cout << car << "\n";

// Output the memory address of car (0x6dfed4)
cout << &car << "\n";

// Output the value of car with the pointer (Honda)
cout << *ptr << "\n";

// Change the value of the pointer
*ptr = "Suzuki";

// Output the new value of the pointer (Suzuki)
cout << *ptr << "\n";

// Output the new value of the car variable (Suzuki)
cout << car << "\n";code-box

Post a Comment

Previous Post Next Post