1. 數組的標誌是 []:
#include <stdio.h>int main(void){ int nums[3]; nums[0] = 11; nums[1] = 22; nums[2] = 33; printf("%d, %d, %d", nums[0], nums[1], nums[2]); getchar(); return 0;}
2. 數組的大小和維數:
#include <stdio.h>int main(void){ int nums[10]; printf("數組大小是: %d\n", sizeof(nums)); printf("數組維數是: %d\n", sizeof(nums)/sizeof(nums[0])); getchar(); return 0;}
3. 遍曆數組:
#include <stdio.h>int main(void){ int nums[10]; int i; for (i = 0; i
對字串數組, 我們也可以這樣想...
#include <stdio.h>int main(void){ char cs[] = "ABCDEFG"; int i; for (i = 0; cs[i]; i++) { /* cs[i] 為假時, 就到了那個Null 字元了 */ printf("%c\n", cs[i]); } getchar(); return 0;}
4. 對一維數組, 可以不指定維數, 它能自動識別:
#include <stdio.h>int main(void){ double ds[] = {1.1, 2.2, 3.3, 4.4}; int count = sizeof ds / sizeof ds[0]; int i; for (i = 0; i
4. 不指定維數的數組常常會用於字串:
#include <stdio.h>int main(void){ char str1[] = "Builder"; /* 假如不怕麻煩可以這樣初始化 */ char str2[8] = {'B','u','i','l','d','e','r','\0'}; unsigned i; for (i = 0; i
5. 二維數組:
#include <stdio.h>int main(void){ int nums[3][4] = { {11,12,13,14}, {21,22,23,24}, {31,32,33,34} }; printf("%d,%d,%d\n", nums[0][2], nums[1][2], nums[2][2]); getchar(); return 0;}
5. 可以並只能省略第一個維數:
#include <stdio.h>int main(void){ int nums[][4] = { {11,12,13,14}, {21,22,23,24}, {31,32,33,34} }; printf("%d,%d,%d\n", nums[0][2], nums[1][2], nums[2][2]); getchar(); return 0;}
6. 多維陣列:
#include <stdio.h>int main(void){ int nums[2][3][4] = { { {111,112,113,114}, {121,122,123,124}, {131,132,133,134} }, { {211,212,213,214}, {221,222,223,224}, {231,232,233,234} } }; printf("%d,%d,%d\n", nums[0][0][0], nums[1][1][1], nums[1][2][2]); getchar(); return 0;}
7. 多維陣列也是可以並只能省略第一個維數:
#include <stdio.h>int main(void){ int nums[][3][4] = { { {111,112,113,114}, {121,122,123,124}, {131,132,133,134} }, { {211,212,213,214}, {221,222,223,224}, {231,232,233,234} } }; printf("%d,%d,%d\n", nums[0][0][0], nums[1][1][1], nums[1][2][2]); getchar(); return 0;}
8. 字串數組:
#include <stdio.h>int main(void){ char css[][10] = { "AAA", "BBB", "CCCCCCC" }; size_t i; for (i = 0; i
9. 沒有初始化的局部陣列變數, 包含的是一堆垃圾值:
#include <stdio.h>int ns1[10]; /* 這個會初始化為空白 */int main(void){ int ns2[10]; /* 這個不會初始化 */ int i; for (i = 0; i
10. 初始化數組為空白其實很簡單:
#include <stdio.h>int main(void){ int ns1[10] = {NULL}; /* 或 {0} */ int ns2[2][3][4] = {0}; int i; for (i = 0; i