Member-only story
Basics of C++ Pointers and Examples with Strings
1 min readMay 19, 2022
What is a pointer?
A pointer is a variable that stores the memory address as its value.
‘&’ is used to get the memory address of the variable.
‘*’ is used to store the memory address of the variable.
How are pointers used?
Here is an example of how to use a pointer in cpp. A variable is first declared with the string “Pizza”. The memory address of the variable ‘food’ is retrieved with ‘&’. How do we store a pointer into a variable? The ‘*’ symbol is used.
Therefore, in this example ‘ptr’ and &food have the same output, the memory address of the string ‘food’.
#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
0x7ffd9c804110
0x7ffd9c804110
How are pointers declared?
string* mystring; // Preferred
string *mystring;
string * mystring;
There are 3 ways to declare pointers. The first way is the most preferred.
}