C++ Pointers C-PLUS-PLUS

C++ Pointers  

C++ Pointers

Creating Pointers

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

A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer.

Example

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

int main() {
  string food = "Pizza";  // A string variable
  string* ptr = &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:

Pizza
0x6dfed4
0x6dfed4

Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're working with.

Use the & operator to store the memory address of the variable called food, and assign it to the pointer.

Now, ptr holds the value of food's memory address.

Get Memory Address and Value

You can also use the pointer to get the value of the variable, by using the * operator (the dereference operator).

Example

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

int main() {
  string food = "Pizza";  // Variable declaration
  string* ptr = &food;    // Pointer declaration

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

  // Dereference: Output the value of food with the pointer
  cout << *ptr << "\n";
  return 0;
}
 

Output:

0x6dfed4
Pizza

Note that the * sign can be confusing here, as it does two different things in our code:
  • When used in the declaration (string* ptr), it creates a pointer variable.
  • When not used in the declaration, it acts as a dereference operator.

 

Modify the Pointer Value

You can also change the pointer's value. But note that this will also change the value of the original variable.

Example

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

int main() {
  string food = "Pizza";
  string* ptr = &food;

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

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

  // Access the memory address of food and output its value
  cout << *ptr << "\n";
  
  // Change the value of the pointer
  *ptr = "Burger";
  
  // Output the new value of the pointer
  cout << *ptr << "\n";
  
  // Output the new value of the food variable
  cout << food << "\n";
  return 0;
}
 

Output:

Pizza
0x6dfed4
Pizza
Burger
Burger

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries