My question is why did they use (int**) in the declaration of the matrix pointer as a pointer to an array. Is it necessary? What difference does it make?
#include <iostream>
using namespace std;
int main()
{
int **matrix; // Pointer to matrix
matrix = (int **) new int *[2]; // Why use (int**) is it necessary?
for (i = 0; i < 2; i++)
matrix[i] = new int[2];
for (i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
matrix[i][j] = j + i;
}
}
It’s unnecessary and potentially dangerous.
The type of the new-expression is already
int**, suitable for assigning tomatrix. There is no need to convert it to its own type.One should not use C-style casts even when a conversion is necessary. Doing so will force a conversion even if it makes no sense, which is a very good way to hide errors; for example, if you accidentally
newthe wrong type: