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].
可以把malloc返回的地址当做一个32位整型值,随意操作。行指针放在分配地址前面,数据放在后面。要注意指针加法操作的不同含义。
template <class T>
T** my2DAlloc(int rows, int cols) {
int header = rows * sizeof(T*);
int data = rows * cols * sizeof(T);
T** ptr2d = (T**)malloc(header + data);
memset((void*)ptr2d, 0, header + data);
T* buff = (T*)(ptr2d + rows);
for (int i = 0; i < rows; ++i) {
ptr2d[i] = buff + i * cols;
}
return ptr2d;
}
template <class T>
void printMatrix(T** matrix, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
template <class T>
void assignMatrix(T** matrix, int rows, int cols, T val) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = val;
}
}
}
int main(int argc, char** argv) {
int rows = 3, cols = 4;
int** matrixi = my2DAlloc<int>(rows, cols);
cout << "Before assignment the matrix is:" << endl;
printMatrix(matrixi, rows, cols);
assignMatrix(matrixi, rows, cols, 5);
cout << "After assignment the matrix is:" << endl;
printMatrix(matrixi, rows, cols);
char** matrixc = my2DAlloc<char>(rows, cols);
cout << "Before assignment the matrix is:" << endl;
printMatrix(matrixc, rows, cols);
assignMatrix(matrixc, rows, cols, 'A');
cout << "After assignment the matrix is:" << endl;
printMatrix(matrixc, rows, cols);
return 0;
}