考慮"hello"
字符串是如何存儲在內存中:讓我們說其'h'
字符的地址恰好是0xC000
。那麼字符串的其餘部分將被存儲如下:
0xC000 'h'
0xC001 'e'
0xC002 'l'
0xC003 'l'
0xC004 'o'
0xC005 '\0'
現在考慮一系列reverse
調用的:初始調用傳遞0xC000
; reverse
來自反向內部的呼叫通過s+1
,所以下一級獲得0xC001
;下一個獲得0xC002
,依此類推。
請注意,每個級別調用下一級,直到看到'\0'
的級別。在我們開始之前爲零,堆棧「裝」是這樣的:
reverse(0xC004) // the last invocation before we hit '\0'
reverse(0xC003)
reverse(0xC002)
reverse(0xC001)
reverse(0xC000) // the earliest invocation
現在當上調用 - reverse(0xC005)
,爲*s
檢查失敗,該函數馬上返回,不打印任何東西。此時堆棧開始「平倉」,無論印刷由其s
說法指出:
0xC004 -> prints 'o', then returns to the previous level
0xC003 -> prints 'l', then returns to the previous level
0xC002 -> prints 'l', then returns to the previous level
0xC001 -> prints 'e', then returns to the previous level
0xC000 -> prints 'h', then returns for good.
這是原"hello"
字符串的反向如何獲取打印。
嘗試手卷的短字符串(「貓」和「狗」彈簧記)通過此功能,並記錄在紙上,一步一個腳印的時候,會發生什麼情況。你可能要先研究指針運算。 – WhozCraig
你可能會絆倒的是該字符串在末尾有一個\ 0,所以'if'語句有一個退出條件。 –
僅供參考你也可以使用std :: reverse –