C語言變長數組
我們知道,傳統的C語言是不能像C++那樣支援變長數組的,也就是說數組的長度是在編譯期就確定下來的,不能在運行期改變。C99標準定義的C語言新特性,新增的一項功能可以允許在C語言中使用變長數組。
C99 gives C programmers the ability to use variable length arrays, which are arrays whose sizes are not known until run time. A variable length array declaration is like a fixed array declaration except that the array size is specified by a non-constant expression. When the declaration is encountered, the size expression is evaluated and the array is created with the indicated length, which must be a positive integer. Once created, variable length array cannot change in length. Elements in the array can be accessed up to the allocated length; accessing elements beyond that length results in undefined behavior. There is no check required for such out-of-range accesses. The array is destroyed when the block containing the declaration completes. Each time the block is started, a new array is allocated.
以上就是C99標準對C語言變長數組的說明.
C語變長數組,測試所用的原始碼很簡單,如下所示:
- //檔案名稱:dynarray.c
- //編譯環境: bloodshed dev-c/c++ 4.9
- #include <stdio.h>
- #define bzero(b,len) (memset((b), '/0', (len)), (void) 0)
- int main(int argc, char *argv[])
- {
- int i, n;
- n = atoi(argv[1]);
-
- char arr[n+1];
- bzero(arr, (n+1) * sizeof(char));
- for (i = 0; i < n; i++) {
- arr[i] = (char)('A' + i);
- }
- arr[n] = '/0';
- printf("%s/n", arr);
- getchar();
- return (0);
- }
上述程式名為dynarray.c,其工作是把參數argv[1]的值n加上1作為變長數組arr的長度,變長數組arr的類型為char。然後向數組中寫入一些字元,並將寫入的字串輸出。
在支援c99標準的IDE上編譯後, 在命令提示字元下,運行:
c:/c99_test/dynarray.exe 6
將輸出:
ABCDEF