Memory & Pointers

Lesson 26
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.
Table of Content

Code

int num = 10;
cout << &num << endl;

int *pNum = &num;
cout << pNum << endl;
cout << *pNum << endl;

In C++, memory refers to the space where the program stores its data and instructions while it is running. Each variable in a C++ program is assigned a location in memory, which is used to store its value. Pointers are variables that store memory addresses, which are used to access the data stored in memory.

Here’s an example of how pointers can be used in C++:

int main() {
  int x = 5;  // create an integer variable and assign it the value 5
  int* ptr = &x;  // create a pointer variable that points to the address of x
  std::cout << "The value of x is: " << x << std::endl; // output the value of x
  std::cout << "The address of x is: " << &x << std::endl; // output the address of x
  std::cout << "The value of ptr is: " << ptr << std::endl; // output the value of ptr
  std::cout << "The value pointed to by ptr is: " << *ptr << std::endl; // output the value pointed to by ptr
  return 0;
}

In this example, we create an integer variable x and assign it the value 5. We then create a pointer variable ptr and assign it the address of x using the address-of operator &. We can access the value of x using the variable x, or by dereferencing the pointer ptr using the dereference operator *.

It’s important to note that when using pointers, we need to be careful to ensure that we don’t accidentally overwrite or access memory that we don’t intend to. This can lead to errors such as segmentation faults or other memory-related errors. It’s also important to properly manage memory allocation and deallocation when working with dynamic memory, such as with arrays or dynamically allocated objects.