# 一維陣列

``````資料型態 名稱[大小];
``````

``````int number[10];    // 宣告 10 個元素的整數陣列
double score[10];  // 宣告 10 個元素的浮點數陣列
char ascii[10];    // 宣告 10 個元素的字元陣列
``````

C99 加入了可變長度的陣列型態（variable length array type），可以使用變數來指定陣列長度，而變數值實際上可以是執行時期運算值，在支援的編譯器下，以下程式碼是可行的：

``````int len = 0;
scanf("%d", &len);
int arr[len];
``````

``````int number[10] = {0};
double score[10] = {0.0};
char ascii[10] = {'\0'};
``````

``````int number[5] = {0, 1, 2, 3, 4};
double score[5] = {87.0, 78.0, 99.5, 69.5, 82.5};
char ascii[5] = {'A', 'B', 'C', 'D', 'E'};
``````

``````#include <stdio.h>
#define LENGTH 10

int main(void) {
int arr[LENGTH] = {0};
int i;

for(i = 0; i < LENGTH; i++) {
printf("%d ", arr[i]);
}
putchar('\n');

for(i = 0; i < LENGTH; i++) {
arr[i] = i;
}

for(i = 0; i < LENGTH; i++) {
printf("%d ", arr[i]);
}
putchar('\n');

return 0;
}
``````

``````0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
``````

``````#include <stdio.h>

int main(void) {
int number[5] = {0, 1, 2, 3, 4};
int length = sizeof(number) / sizeof(number[0]);

for(int i = 0; i < length; i++) {
printf("%d ", number[i]);
}
printf("\n");

return 0;
}
``````

``````int number[5] = {98, 76};
double weight[5] = {0.0, 0.1};
char ch[5] = {'A', 'B'};
``````

``````int number[] = {1, 2, 3};
double weight[] = {0.4, 3.2, 1.0, 4.2};
char ch[] = {'A', 'B'};
``````

``````const int number[] = {1, 2, 3};
number[1] = 10; // error: assignment of read-only location 'number[1]'
``````

``````int arr1[5];
int arr2[5];
...
arr1 = arr2; // 錯誤！不能直接指定陣列給另一個陣列
``````

``````int arr1[LEN];
int arr2[LEN];
...
for(int i = 0; i < LEN; i++) {
arr1[i] = arr2[i];
}
``````