Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Pointer to Pointer Dynamic Allocation | Dynamic Memory Allocation
C++ Pointers and References

book
Pointer to Pointer Dynamic Allocation

A pointer to pointer, denoted as double pointer (**).

This is a pointer that holds the memory address of another pointer. In simple words, it is a variable whose value is the address of another pointer. This concept might sound complex at first, but it provides a powerful mechanism for dealing with advanced dynamic memory allocation.

Syntax

main.cpp

main.cpp

copy
#include <iostream>

int main()
{
int x = 10;
int *ptr1 = &x;
int **ptr2 = &ptr1;

// Accessing values using double pointer
std::cout << "Location of ptr2: " << ptr2 << std::endl;
std::cout << "Location of ptr1: " << *ptr2 << std::endl;
std::cout << "Value of x: " << **ptr2 << std::endl;
}
12345678910111213
#include <iostream> int main() { int x = 10; int *ptr1 = &x; int **ptr2 = &ptr1; // Accessing values using double pointer std::cout << "Location of ptr2: " << ptr2 << std::endl; std::cout << "Location of ptr1: " << *ptr2 << std::endl; std::cout << "Value of x: " << **ptr2 << std::endl; }
  • ptr1: is a pointer to an integer (int*);

  • ptr2: is a double pointer to an integer (int**).

Dynamic Allocation of a Two-Dimensional Array

If you want to create a two-dimensional array dynamically (at runtime) you have to use a pointer to a pointer for the rows.

And then initialize each row with dynamic array (like in previous chapter)

Compito

Swipe to start coding

  • Dynamically allocate a two dimensional array.
  • Dynamically allocate the arrays as elements.
  • Free all allocated memory.

Soluzione

solution.cpp

solution.cpp

#include <iostream>

int main()
{
int rows = 3, columns = 5;
int **twoDArray = new int*[rows];
for (int row = 0; row < rows; row++)
twoDArray[row] = new int[columns];
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
{
twoDArray[row][column] = row * columns + column;
std::cout << twoDArray[row][column] << ' ';
}
for (int row = 0; row < rows; row++)
delete[] twoDArray[row];
delete[] twoDArray;
}

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 4
single

single

#include <iostream>

int main()
{
int rows = 3, columns = 5;
int __twoDArray = ___ int_[rows];
for (int row = 0; row < rows; row++)
twoDArray[row] = ___ int[columns];

// Initialization of the array with some values
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
{
twoDArray[row][column] = row * columns + column;
std::cout << twoDArray[row][column] << ' ';
}

for (int row = 0; row < rows; row++)
___[] twoDArray[_];
___[] twoDArray;
}

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt