I have the following function which creates a 2D array
double** createMatrix(int r, int c)
{
double** matrix = (double**)malloc(r * sizeof(double*));
if (matrix) {
for (int i = 0; i < r; i++) {
matrix[i] = (double*)malloc(c * sizeof(double));
if (matrix[i]) {}
else {
printf("Memory not allocated.\n");
free(matrix[i]);
exit(0);
}
}
}
else {
printf("Memory not allocated.\n");
free(matrix);
exit(0);
}
return matrix;
}
I want to define a template for this function allowing it to create a matrix of generic type but this seems not working:
template <typename T>
T** createMatrix(int r, int c)
{
T** matrix = (T**)malloc(r * sizeof(T*));
if (matrix) {
for (int i = 0; i < r; i++) {
matrix[i] = (T*)malloc(c * sizeof(T));
if (matrix[i]) {}
else {
printf("Memory not allocated.\n");
free(matrix[i]);
exit(0);
}
}
}
else {
printf("Memory not allocated.\n");
free(matrix);
exit(0);
}
return matrix;
}
where is the problem?