动态创建二维数组

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
26
27
28
29
#include <stdlib.h>
#include <string.h>
int **(int x, int y) {
int **a = (int **) malloc(sizeof(int *) * x);
int *b = (int *) malloc(sizeof(int) * y);
int *c = (int *) malloc(sizeof(int) * y);
b[2] = 100;
a[0] = b;
a[1] = c;
return a;
}
int main(int argc, char **argv) {
int x = 2;
int y = 10;
int **a = createArr(x, y);
printf("a = %d n", a[0][2]);
for (int i = 0; i < x; i++) { // 释放指针
free(a[i]);
}
free(a); // 释放指针
return 0;
}