?C語言中動態分配數組(一維)
?
??? 當初學Pascal的時候就想過這個問題:如何動態的定義及使用數組呢?記得一般用數組的時候都是先指定大小的。當時問老師,老師說是不可以的。后來又問了一位教C++的老師,他告訴我在C++里用new可以做到,一直不用C++,所以也不明白。今天在逛論壇時終于找到了C語言中的用法(看原貼):
??? int *a;
??? int N;
??? scanf("%d", &N);
??? a = (int *) malloc(N * sizeof(int));
??? ....
??? free(a);
??? 這樣就動態分配了數組a[N]。數組的長度N可輸入確定,也可用程序中的變量確定。但要注意程序結束后要用free()將其釋放,否則內存會泄漏。
--------------------------------------------------------------------------------
驗證一下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
??? int i = 0;
??? int *a;
??? int N;
??? printf("Input array length: ");
??? scanf("%d", &N);
??? printf("\n");
??? a = (int *) malloc(N * sizeof(int));
???
??? for(i = 0; i < N; i++)
??? {
??????? a[i] = i + 1;
??????? printf("%-5d", a[i]);
??????? if ((i + 1) % 10 == 0)
??????????? printf("\n");
??? }
??? free(a);
??? printf("\n");???
??? return 0;
}
運行結果(VC):
=========================================================
Input array length: 100↙
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
51?? 52?? 53?? 54?? 55?? 56?? 57?? 58?? 59?? 60
61?? 62?? 63?? 64?? 65?? 66?? 67?? 68?? 69?? 70
71?? 72?? 73?? 74?? 75?? 76?? 77?? 78?? 79?? 80
81?? 82?? 83?? 84?? 85?? 86?? 87?? 88?? 89?? 90
91?? 92?? 93?? 94?? 95?? 96?? 97?? 98?? 99?? 100
=========================================================
?