运算子对阵列做随机存取.pptVIP

  • 0
  • 0
  • 约4.06千字
  • 约 21页
  • 2018-04-21 发布于天津
  • 举报
运算子对阵列做随机存取

Chapter 5 複合資料型態 簡介 陣列 字串 結構 陣列 這是最經典的資料結構 相同資料型別, 固定長度的序列 對於任何資料型別都適用 使用[]運算子對陣列做隨機存取 存取區間介於 0 ~ size-1 陣列內容倒轉輸出 #include stdio.h #include stdlib.h #define SIZE 10 int main(int argc, char *argv[]) { int i, n, input; int ns[SIZE]; for (n = 0; n SIZE; n++) { scanf(%d, input); if (input == 0) break; ns[n] = input; } for (i = n - 1; i = 0; i--) printf(%d , ns[i]); system(pause); return 0; } 陣列的初始化 可以使用列表初始化: int a[] = {1O,20,30,40,50}; 可以選擇給定維度 如果給定,必須要大於列表 通常用於零初始化 如果不給定,維度自動依列表初始化決定 多維度陣列 C並不存在多維度陣列 C,C++,JAVA 都允許陣列中有陣列 必須使用一個陣列來容納其他陣列 可以使用巢狀列表初始化 Example 2維陣列 3 x 2 : 1 2 3 4 5 6 C 儲存線性: 1 2 3 4 5 6 編譯器解釋為3個2元素陣列 Example #include stdio.h #include stdlib.h int main(int argc, char *argv[]) { int a[][2] = {{1, 2}, {3, 4}, {5, 6}}; int i, j; for (i = 0; i 3; ++i) { for (j = 0; j 2; ++j) printf(%d , a[i][j]); printf(“\n”); } system(pause); return 0; } /* 1 2 3 4 5 6 */ 3維陣列 例子將示範如何建立以下3維列陣: 1 2 7 8 3 4 == a[0] 9 0 == a[1] 5 6 1 2 Example #include stdio.h #include stdlib.h int main(int argc, char *argv[]) { int a[][3][2] = {{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 0}, {1, 2}}}; int i, j, k; for (i = 0; i 2; ++i){ for (j = 0; j 3; ++j){ for (k = 0; k 2; ++k) printf(%d , a[i][j][k]); printf(\n); } printf(\n); } system(pause); return 0; } 字串 字元陣列 字串結束將跟隨 null byte (\0) C++ 和 Java 具有較佳的字串處理能力 字串將自動增加\0: “hello” 變為: h e l l o \0 字串範例 #include stdio.h #include string.h #include stdlib.h int main(int argc, char *argv[]) { char s1[] = {c, h, r, i, s, \0}; char s2[] = rebots; printf(s1 == %s\n, s1); printf(s2 == %s\n, s2); printf(s1 has %d chars\n, strlen(s1)); printf(s2 has %d chars\n, strlen(s2)); system(pause); return 0; }/* s1 == chris s2 == rebots s1 has 5 chars s2 has 6 chars */ string.h 本函式庫包含常用的字串指令 多數假設字串尾部跟隨 NULL strcpy, strcat, memcpy strcmp, memcmp strchr, memchr, strrchr, strstr, strtok 例子 #include stdio.h #include stdlib.h int main(int argc, char *argv[]) { int n = 1; float x = 2.0;

文档评论(0)

1亿VIP精品文档

相关文档