forked from fanspaceshow/CodeTemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_array.c
50 lines (43 loc) · 976 Bytes
/
dynamic_array.c
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <stdlib.h>
/*
* 定义一维数组
*/
void defOneDimArray(int n) {
int *arr = (int*)calloc(n, sizeof(int));
int i;
for(i = 0; i < n; i++) {
arr[i] = i;
}
for(i = 0; i < n; i++) {
printf("i is %d and arr[i] is %d \n", i, arr[i]);
}
//需要释放内存
free(arr);
}
void defTwoDimArray(int m, int n) {
int **arr = (int **)calloc(m, sizeof(int *));
int i, j, index = 0;
for(i = 0; i < m; i++) {
arr[i] = (int *) (calloc(n, sizeof(int)));
}
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
arr[i][j] = index;
index++;
}
}
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("i is %d and j is %d and arr[i][j] is %d\n", i, j, arr[i][j]);
}
}
for(i = 0; i < m; i++) {
free(arr[i]);
}
free(arr);
}
int main() {
defOneDimArray(10);
defTwoDimArray(2, 3);
}