Skip to content

Commit b4cdcd7

Browse files
authored
Update 动态分配数组大小.c
1 parent 4ee2a29 commit b4cdcd7

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed
Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,43 @@
1-
#
1+
//我们知道,C语言中的数组大小是固定的,定义的时候必须要给一个常量值,不能是变量。
2+
3+
//这带来了很大的不便,如果数组过小,不能容下所有数组,如果过大,浪费资源。
4+
5+
//下面的代码实现了简单的动态数组:
6+
7+
#include <stdio.h>
8+
#include <stdlib.h>
9+
10+
int main()
11+
{
12+
//从控制台获取初始数组大小
13+
int N;
14+
int *a;
15+
int i;
16+
17+
printf("Input array length:");
18+
scanf("%d\n",&N);
19+
20+
//分配空间
21+
a=(int *)calloc(N,sizeof(int));
22+
//填充数据
23+
for(i=0;i<N;i++){
24+
a[i]=i+1;
25+
printf("%-5d",a[i]);
26+
if((i+1)%10==0){
27+
printf("\n");
28+
}
29+
}
30+
//释放内存
31+
free(a);
32+
a=NULL;
33+
34+
printf("\n");
35+
return 0;
36+
}
37+
38+
39+
//运行结果:
40+
//Input array length:20
41+
42+
//1 2 3 4 5 6 7 8 9 10
43+
//11 12 13 14 15 16 17 18 19 20

0 commit comments

Comments
 (0)