1 / 12

程式設計 C 語言 第八章 指位器與陣列

程式設計 C 語言 第八章 指位器與陣列. 鄧姚文 joseph@im.knu.edu.tw http://w3.im.knu.edu.tw/~joseph/. 指位器. & 取得位址 * 透過位址取值. 以指位器傳遞引數. 傳值呼叫 函式內的運算不影響原變數內容 void foo(int x, int y) 傳址呼叫 函式內的運算會改變原變數內容 void foo(int* x, int* y). 指位器與陣列的關係. 陣列名稱本身就是指位器 指位器的運算 指位器 +1 :指向下一個元素 指位器 -1 :指向上一個元素

iram
Download Presentation

程式設計 C 語言 第八章 指位器與陣列

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 程式設計 C 語言第八章 指位器與陣列 鄧姚文 joseph@im.knu.edu.tw http://w3.im.knu.edu.tw/~joseph/

  2. 指位器 • & 取得位址 • * 透過位址取值

  3. 以指位器傳遞引數 • 傳值呼叫 • 函式內的運算不影響原變數內容 • void foo(int x, int y) • 傳址呼叫 • 函式內的運算會改變原變數內容 • void foo(int* x, int* y)

  4. 指位器與陣列的關係 • 陣列名稱本身就是指位器 • 指位器的運算 • 指位器+1:指向下一個元素 • 指位器-1:指向上一個元素 • 位址差距=sizeof(*ptr) • 比較運算 • 在同一個陣列內 • > < == !=

  5. 多維陣列 • 型別 陣列名[m][n]… • 陣列初始值 • char s[3][4] = {{‘a’, ‘b’, ‘c’, ‘\n’}, {‘d’, ‘e’, ‘f’, ‘\0’}, {‘g’, ‘h’, ‘i’, ‘\0’}}; • char names[][] = { “abc”, “def”, “ghi”}; • char* names [] = { “abc”, “def”, “ghi”};

  6. 命令列參數的引入 • void main(int argc, char* argv[]) • argc 為命令列參數的數量 • argv[0] 為命令本身 • find . -name core -print • argc = 5 • argv[0] = “find” • argv[1] = “.” • argv[2] = “-name” • argv[3] = “core” • argv[4] = “-print”

  7. 將字串轉成數值 • #include <stdlib.h> • double atof(const char* s); • int atoi(const char* s); • long aotl(const char* s);

  8. 動態記憶體配置 • void *malloc(size_t size); • 配置記憶體 size bytes • void free(void *ptr); • 歸還記憶體

  9. 泡沫排序法 Bubble Sort • 每一回合以兩兩比較的方式將數列中最大的值放在數列的最右邊 • 第1回合比出第1大的值,放在右邊第1個位置 • 第2回合比出第2大的值,放在右邊第2個位置 • … • 第n-1回合比出第n-1大的值,放在右邊第n-1個位置 • 經過 n-1 個回合後排序完成 • 第 i 個回合需要作 n-i 次比較 • 共需 (n-1)+(n-2)+…+1=n*(n-1)/2 次比較 • O(n2)

  10. 搜尋(Search) • 尋找某一筆資料 • 確認其位置 • 判斷該筆資料是否存在 • 線性搜尋 Sequential Search • O(N) • 二分搜尋法 Binary Search • O(log2 N) • 資料必須先排序

  11. 字串處理 • 字串即字元陣列 • 字串必須以 ‘\0’結尾 • #include <string.h> • size_t strlen(const char *s); • 傳回字串長度 • int strcmp(const char *s1, const char *s2); • 比較字串大小 • 傳回值 == 0:兩字串相等 • 傳回值 > 0:s1 > s2 • 傳回值 < 0:s1 < s2

  12. 字串處理 • int strncmp(const char *s1, const char *s2, size_t n); • 比較字串前n個字元的大小 • 傳回值 == 0:兩字串相等 • 傳回值 > 0:s1 > s2 • 傳回值 < 0:s1 < s2 • char *strcpy(char *dest, const char *src); • 複製字串 • char *strncpy(char *dest, const char *src, size_t n); • 複製字串,n個字元 • 用來取子字串

More Related