Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende 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

cpp

main

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)

Tarea

Swipe to start coding

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

Solución

cpp

solution

#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;
}

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
#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;
}

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

We use cookies to make your experience better!
some-alt