Hi Everyone, I am Shafiul Islam. I am beginer in C and C++. Recently I wrote a piece of code on Template and Malloc(). But I am afraid about the hidden bug. It works file till now for a small matrix and vector though. I want to keep this code as more accurate. If any expat can have a look on my code and give me some recommendation if there is any hidden bug inside of my code.
Code:
#include <stdlib.h>
#include <typeinfo>
#include <cstring>
#include<iostream>
template <class type1, class type2>
void allocateData1DbyMalloc(type1** data1D, type2 nRow) {
int size = (char*) &(*data1D)[1] - (char*) & (*data1D)[0];
*data1D = (type1*)malloc(nRow * size); // sizeof(type1));
}
template <class type1>
void deAllocateData1DbyFree(type1** data1D) {
free(*data1D);
}
template <class type1, class type2>
void allocateData2DbyMalloc(type1*** data2D, type2 nRow, type2 nColumn) {
int size = (char*) & (*data2D)[1] - (char*) & (*data2D)[0];
*data2D = (type1 * *)malloc(size * nRow); // sizeof(type1*)
if (*data2D) {
size = (char*) & (**data2D)[1] - (char*) & (**data2D) [0];
for (int i = 0; i < nRow; i++) {
(*data2D)[i] = (type1*)malloc(size * nColumn); // sizeof(type1)
}
}
}
template <class type1, class type2>
void destroyMatrix2DbyFree(type1*** data2D, type2 numberOfRow) {
for (int row = 0; row < numberOfRow - 1; row++)
free((*data2D)[row]);
free(*data2D);
}
int main() {
int n = 4;
// std::cin >> n;
double* constrainVector;
allocateData1DbyMalloc(&constrainVector, n);
constrainVector[0] = 16.0;
constrainVector[1] = 25.6;
constrainVector[2] = -11.2;
constrainVector[3] = 12.7;
for (int i = 0; i < n; i++)
std::cout << i << " " << constrainVector[i] << std::endl;
deAllocateData1DbyFree(&constrainVector);
double** matrix2D;
allocateData2DbyMalloc(&matrix2D, n, n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix2D[i][j] = (double)(i+j);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
std::cout << i << j << " " << matrix2D[i][j] << std::endl;
}
destroyMatrix2DbyFree(&matrix2D, n);
return 0;
}