Module lessons (2/2)
Pointers
Pointers are one of the most powerful and distinctive features of C++. They allow you to access the physical memory of the computer directly, enabling efficient resource management and high performance.
1. What is Memory and an Address?
Every variable you declare in your program is stored in a cell of the RAM memory. Each cell has a unique memory address (usually expressed in hexadecimal format, e.g., 0x7ffee3bf87ac).
C++ allows us to get the memory address of any variable using the address-of operator &:
int x = 42;
std::cout << &x; // Prints the memory address of x (e.g., 0x7ffee3bf87ac)
2. Definition of a Pointer
A pointer is a special variable that stores the memory address of another variable as its value.
The syntax requires the use of the asterisk * after the data type:
int x = 42;
int* ptr = &x; // ptr is a pointer to an integer that contains the address of x
3. The Dereference Operator (*)
To access or modify the value stored at the address a pointer points to, we use the dereference operator (or indirection operator), also represented by the symbol *:
int x = 42;
int* ptr = &x;
std::cout << *ptr; // Prints 42 (the value ptr points to)
*ptr = 100; // Modifies the value of x through the pointer
std::cout << x; // Now prints 100!
4. Null Pointers: nullptr
A pointer that does not point to any valid address should be initialized with the nullptr keyword (introduced in C++11):
int* ptr = nullptr; // Safe null pointer
Try it yourself
In main, there is an integer variable value initialized to 42. Declare a pointer to integer ptr that points to the address of value. Use the dereferencing of ptr to set the value of value to 100, and finally print value using std::cout.
Show hint
Dichiara il puntatore con `int* ptr = &value;`, modifica il valore dereferenziando `*ptr = 100;`, e stampa `std::cout << value;`.
Solution available after 3 attempts
Define a function doubleValue that accepts a pointer to an integer (int* ptr) and multiplies the value it points to by 2 (if the pointer is not null). In main, call doubleValue passing the address of the variable num and print it.
Show hint
La funzione deve accettare `int* ptr`. All'interno, usa `*ptr = (_ptr) _ 2`. Nel main chiamala con `doubleValue(&num);`.
Solution available after 3 attempts
Given the code provided, which expression allows you to directly modify the value of a, setting it to 10?
int a = 5;
int* p = &a;
// quale istruzione assegna 10 ad a?