[CS]CS50 Week 2: Array

Penny Ng
3 min readSep 15, 2020

--

Assignment 1: Readability

Spec:

Your program should count the number of letters, words, and sentences in the text, and then print out the grade level computed by the Coleman-Liau formula, rounded to the nearest integer.

這個作業比較簡單,寫一個for loop逐字檢視user輸入的text,並使用官方提供ctype.h檢查目前的字是不是文字、空格、標點符號,最後將得到的字母數、單字數、句數運算並丟進Coleman-Liau formula即可得到index。

Assignment 2: Caesar

Spec:

Implement a programme that encrypts messages using Caesar’s cipher.

Your programme must accept a single command-line argument, a non-negative integer, as a “key”. Do not assume that key will be less than or equal to 26. Your programme should then prompt the user for a string of text. Each alphabetical character of that plaintext should be rotated by a certain positions according to the key in order to encrypt the plaintext. The programme preserves case though — lowercase letters remain lowercase, and uppercase letters remain uppercase. And the non-alphabetical characters remain unchanged.

Command-line argument

寫一個function判斷user從command line輸入的參數數量,以及是否為非負的整數。

Encipher text

寫一個function來encipher text。使用 key % 26得到需要rotate的位數。將大小寫的字母平移到0–25,做完運算key的運算再平移回去,即可完成加密,並保有原本的大小寫。

Memory

從function encipher_text回傳加密完成的ciphertext時遇到了記憶體的問題。一開始在function宣告一個變數ciphertext,並在最後return這個變數ciphertext,結果跳出了Warning — address of stack memory associated with local variable ‘ciphertext’ returned。

回答提到 this variable is declared on stack, and it will be automatically released when current block goes out of the scope. This means when you return matches, memory reserved for matches will be freed, and your pointer will point to something that you don't want to.

最後使用回答中的第2個方法順利解決。

Array & String

  • 在C語言中,我們無法直接assign一個array到另一個array
  • 一個String的最後一個位元為‘\0’
  • 因此儲存一個string實際需要的位元數為n+1,最後一位元為\0

因為沒有注意到string最後一位元為\0以及記憶體分配的問題,使用check50檢查時一直出現不知名的錯誤,就跟下面這個stack overflow的發問一模一樣,經過修正後就順利過關了!

--

--

Penny Ng

A passionate self-taught  iOS developer. Write to record my learning and share the knowledge