在 C 中初始化變長陣列
變長陣列是其長度在執行時而不是編譯時確定的資料結構。這些陣列有助於簡化數值演算法程式設計。C99 是一種允許變長陣列的 C 程式設計標準。
如下所示,使用 C 示範變長陣列的程式:
示例
#include int main(){ int n; printf("Enter the size of the array:
"); scanf("%d", &n); int arr[n]; for(int i=0; i<n; i++) arr[i] = i+1; printf("The array elements are: "); for(int i=0; i<n; i++) printf("%d ", arr[i]); return 0; }
輸出
上述程式的輸出如下所示:
Enter the size of the array: 10 The array elements are: 1 2 3 4 5 6 7 8 9 10
現在,讓我們瞭解一下上述程式。
在上述程式中,陣列 arr[] 是一個變長陣列,因為其長度是由使用者提供的 run time 值確定的。展示此操作的程式碼段如下所示:
int n; printf("Enter the size of the array:
"); scanf("%d", &n); int arr[n];
陣列元素使用 for 迴圈初始化,然後顯示這些陣列元素。展示此操作的程式碼段如下所示:
for(int i=0; i<n; i++) arr[i] = i+1; printf("The array elements are: "); for(int i=0; i<n; i++) printf("%d ", arr[i]);
廣告