Solution
#include <iostream>
using namespace std;
int** malloc2d(int rows, int cols)
{
int header = rows * sizeof(int*);
int data = rows * cols * sizeof(int);
int** rowptr = (int**)malloc(header + data);
int* buf = (int*)(rowptr + rows);
int k;
for (k = 0; k < rows; ++k) {
rowptr[k] = buf + k*cols;
}
return rowptr;
}
int free2d(int** pt)
{
free(pt);
return 0;
}
int main(int argc, char* argv[])
{
int i, j;
int **p = malloc2d(3,5);
for( i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
p[i][j] = i + j;
cout << p[i][j] << " ";
}
cout << endl;
}
free2d(p);
return 0;
}
Problem
Write a function called my2DAlloc which allocates a two dimensional array. Minimize the number of calls to malloc and make sure that the memory is accessible by the notation arr[i][j]