[轉]C語言構建動態數組完整實例
原文地址:http://www.jb51.net/article/52153.htm
本文以一個完整的實例代碼簡述了C語言構建動態數組的方法,供大家參考,完整實例如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18#include <stdio.h>
#include <malloc.h>
int main(void) {
int len;
int * arr;
printf("請輸入數組長度:");
scanf("%d", &len);
arr = (int *)malloc(sizeof(int)*len);
printf("請輸入數組的值:");
for ( int i = 0; i < len; i ++) {
scanf("%d", &arr[i]);
}
for (int j = 0; j < len; j ++) {
printf("%d:%d ", j , arr[j]);
}
free(arr);
return 0;
}
運行結果如下:
? 1 2 3 4 5E:\clearning\cpointer>gcc dynamicarray.c -o dm --std=c99
E:\clearning\cpointer>dm
請輸入數組長度:5
請輸入數組的值:1 2 3 4 5
0:1 1:2 2:3 3:4 4:5