sysprog2018
contributed by < goho302jo03
>
不同的 CPU 儲存資料的方式會有差異,將低序字節儲存在起始位址的稱作 little-endian;將高序字節存在起始位址的稱作 big-endian。
Union 是一種將不同 data types 儲存在同一個記憶體空間的特殊自訂型別,一次只會儲存一個變數資料,且會以宣告的變數型態 size 最大的變數空間作為記憶體空間。
先測試 union 的大小
接著測試是否共用同一段記憶體
因為 union 內的變數共用同一塊記憶體,且 int 為 4 bytes,char 為 1 個 bytes,所以若 c.a 輸出 0xa41df930 則 c.b 輸出 0x30
若上面程式碼改成
為什麼輸出會是
而不是
如果是 big-endian ,則 c.b 會取到下面紅框內的值
如果是 little-endian ,則 c.b 會取到下面紅框內的值
考慮以下程式碼:
在 struct 結構型態中,可以定義各種不同長度的 bit 位元型態,以節省儲存空間
呈現以下這種情況
共需要 16 bytes 的記憶體空間
以上這段程式碼的輸出結果會是
以我的理解,下面這段程式碼更改成了 short gg;
,應該輸出結果會不變
可是輸出結果卻是
想請問一下記憶體配置會是像下面這樣嗎
還是說其實我哪裡弄錯了,謝謝
The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.
考慮到以下程式碼:
該如何修改,才能讓 func 得以變更到 main 裡頭 ptrA 的內含值?
參考 你所不知道的C語言:指標篇 的範例
會輸出以下
從這個例子中可以知道 ptrA 並不會被改變
將程式碼改成以下
傳給 p 的值由 ptrA 變成 &ptrA,接著將 &B 賦值給 *p,且因為 &ptrA = p ,所以就能夠改到 ptrA 的值。
考慮到以下程式碼:
指出存在的問題和提出修正機制,需要用 C99/C11 規格解釋。
C99/C11 6.2.4
object referred out of lifetime is undefined behavior
- An object has a storage duration that determines its lifetime. There are four storage durations: static, thread, automatic, and allocated. Allocated storage is described in 7.22.3.
- The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
推敲以下程式碼的作用:
以上這段程式碼是將 10 進位的數值轉換成 16 進位的數值,
將第 6 行刪掉較不會混淆