2.2: How to use a pointer
- Page ID
- 34647
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
How to use a pointer?
- Define a pointer variable – you must use an asterisk (*) when defining a pointer variable. All three of the following are valid – they are the same:
-
- int *ptr;
- int * ptr;
- int* ptr;
- Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that variable.
- Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.
The reason we associate data type to a pointer is that it knows how many bytes the data is stored in. When we increment a pointer, we increase the pointer by the size of data type to which it points.
// C++ program to illustrate Pointers in C++ #include <iostream> using namespace std; int main() { int var = 20; // declare pointer variable int *ptr; // assignment happens at time of definition: // it would be: int *ptr = &var; // note that data type of ptr and var must be same // also note the absence of the * during this assignment ptr = &var; // assign the address of a variable to a pointer cout << "Value at ptr = " << ptr << endl; cout << "Value at var =" << var<< endl; cout << "Value at *ptr =" << *ptr<< endl; return 0; }
Output:
Value at ptr = 0x7ffcb9e9ea4c
Value at var = 20
Value at *ptr = 20
Adapted from:
"Pointers in C/C++ with Examples" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0