Skip to content

[C++] Tutorial(6): Pointer and Reference

Pointer is a special data type in C++ that stores variable memory address. It is often used to build structure such as Linked List or to transfer large data memory address to improve program efficiency.

By the way, the pointer is declared using asterisks (*).

Reference is like creating another alias for the variable (or object), and our operation on the reference will be like operating the original object.

The following I will record some simple program to demo how to use pointer and reference.


Pointer

The meaning of pointer is just storing the memory address. It is not as complicated as many people imagine.

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

int main() {
    int n = 10;
    cout << "n: " << n << endl;
    cout << "n adress: " << &n << endl << endl;

    // Pointer
    int *p = &n;
    cout << "*p: " << *p << endl;
    cout << "p: " << p << endl << endl;

    // Add
    *p += 10;
    cout << "n: " << n << endl;
    cout << "n address: " << &n << endl;
    cout << "p: " << p << endl;

    return 0;
}



Output:

n: 10
n adress: 0x7ffee7423a98

*p: 10
p: 0x7ffee7423a98

n: 20
n address: 0x7ffee7423a98
p: 0x7ffee7423a98

The n variable is a INT data type variable, and &n is its memory address. We can use int *p or int* p to store its memory address.

We can also reassign the value of n through operating *p.

But it is difficult to understand why we need to use pointer in the program through such a simple example. You have to build a Linked-List by yourself and understand the benefits of not using contiguous memory.


Reference

Reference just like an alias for a variable. We can also affect the original variable value through reference variable.

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

int main() {
    int n = 10;
    cout << "n: " << n << endl << endl;

    // Reference
    int &r = n;
    cout << "r: " << r << endl << endl;

    // Add
    r += 10;
    cout << "n: " << n << endl;
    cout << "r: " << r << endl;

    return 0;
}



Output:

n: 10

r: 10

n: 20
r: 20

References


Read More

Tags:

Leave a Reply