Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Pointers

Pointers

Pointers are variables that store memory addresses. They provide a way to access and manipulate memory directly. Pointers are powerful but also require careful handling to avoid common pitfalls like memory leaks and undefined behavior.

Creating pointer

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

int main() {
  string food = "Burger";

  cout << food << "\n";
  cout << &food << "\n";
  return 0;
}

Output:

Burger
0x7ffdd95a85d0


A pointer in C++ serves as a variable specifically designed to hold memory addresses. It stores the location in memory where another variable resides. Pointer variables are created using the asterisk (*) operator, and they are assigned the memory address of a variable of the same data type. This address allows the pointer to “point to” or reference the value stored in that variable directly.

Example:

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

int main() {
  string food = "Burger";  // 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:

Burger
0x7ffe86211ad0
0x7ffe86211ad0

    Leave a Reply

    Your email address will not be published.

    Need Help?