forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.10.cpp
More file actions
25 lines (24 loc) · 635 Bytes
/
16.10.cpp
File metadata and controls
25 lines (24 loc) · 635 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <malloc.h>
using namespace std;
int** My2DAlloc(int rows, int cols){
int **arr = (int**)malloc(rows*sizeof(int*));
for(int i=0; i<rows; ++i)
arr[i] = (int*)malloc(cols*sizeof(int));
return arr;
}
int** My2DAlloc1(int rows, int cols){
int header = rows * sizeof(int*);
int data = rows * cols * sizeof(int);
int **arr = (int**)malloc(header + data);
int *buf = (int*)(arr + rows);
for(int i=0; i<rows; ++i)
arr[i] = buf + i * cols;
return arr;
}
int main(){
int **arr = My2DAlloc1(4, 5);
arr[2][3] = 23;
cout<<arr[2][3]<<endl;
return 0;
}