c++ print array of arrays with pointer
To print an array of arrays in C++ using pointers, you can follow these steps:
Declare and initialize your array of arrays. In this example, let's say we have a 2D array of integers with dimensions
rows
andcolumns
:cpp int arr = new int*[rows]; for (int i = 0; i < rows; i++) { arr[i] = new int[columns]; }
Populate the array with values. You can use nested loops to iterate through each element and assign a value. For example:
cpp for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { arr[i][j] = i + j; // Assigning a value to each element } }
Print the array of arrays using pointers. You can use nested loops again to iterate through each element and print its value. For example:
cpp for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { cout << arr[i][j] << " "; // Printing each element } cout << endl; // Moving to the next line after each row }
Deallocate the memory. Since you allocated memory dynamically using
new
, it's important to free it to avoid memory leaks. You need to deallocate both the arrays and the array of pointers. For example:cpp for (int i = 0; i < rows; i++) { delete[] arr[i]; // Deallocating each row } delete[] arr; // Deallocating the array of pointers
Here is the complete code snippet:
#include <iostream>
using namespace std;
int main() {
int rows = 3;
int columns = 4;
int arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[columns];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = i + j;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;
return 0;
}
This code will create a 2D array, populate it with values, print the array, and then deallocate the memory to avoid memory leaks.