2020q1 Homework2 (quiz2)
contributed by < pingsutw
>
重新回答第 2 周測驗題
解題思路
xs_new
分別依據 len
大小,來判斷新的字串要存 heap or stack, 當字串大於 16 時,資料存在 heap,所以這邊 AAA
代表 16
BBB = 32
因為 char 0~255 分別代表不同字元,mask 每單位代表 8 個字元 8*32 = 256
, 每個 bit 分別代表 char 不同字元
CCC = &
因為 mask 裡的每個 bit 代表要刪除的字元,跟 mask 裡的每個 bit 做 &,如果是0代表沒有找到符合的字元,反之刪除此字元
延伸問題
xs_copy
字串在 stack 時,複製 string 到 dest,當字串存在 heap 時,有指針指向 src的 data,避免在大字串額外的記憶體複製
- cow (Copy on write)
加一個 int pointer 表示 refernece count, refcnt = NULL, 代表沒有其他指標指向同一快記憶體空間 ptr,反之 > 1 代表有 1 個以上同時指向同一個記憶體空間
測試
- 先做 concat 讓 string 存在 heap 裡
- copy string,此時不會新增一段新的記憶體空間,而是指標指向 string 的位址
- 對 copy string 做 trim 此時才會新增新的記憶體空間,並對字串進行修改,可發現記憶體位址跟 string 已經不一樣了
輸出結果
xs_strtok
- 將字串分割成一個個片段, x 欲被分解的字串, delim 分隔的字串(符號), 用
strspn
找出分解後的字串的起始點,strpbrk
找出分解後的字串的的終點,並設為 \0
代表字串
lastToken
代表下一個分解後的字串的起始點
測試
輸出結果
程式優化
TODO (Kevin) 重新測量,把 outlier 去除
輸出結果
參考資料
- [size_t strspn(const char *str1, const char *str2)](http://tw.gitbook.net/c_standard_library/c_function_strspn.html)
- [char *strpbrk(const char *str1, const char *str2)](http://tw.gitbook.net/c_standard_library/c_function_strpbrk.html)
關於 C 標準函式庫的參考資料,務必以 Linux man page 為主,方可知道語言規範和實作的議題。避免閱讀第 N 手材料
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
jserv
- C 語言:typedef 的用法
改為查閱 C 語言規格書!
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
jserv