※ 引述《forris (喬巴)》之銘言:
: 假設一個字元 (character) 佔一個 byte,一個整數 (integer) 佔兩個 byte,在記憶體
: 中,一個字組 (word) 相當於兩個 bytes,字元可以儲存於任何位址,而整數則必須儲存
: 於一整個字組中。現在以 C 定義一資料結構如下:
: struct person {
: int id;
: char name[20];
: int age;
: char sex;
: } student[100];
: 若 student[0] 之起始位址為 200 (十進位),請問 student[10].age 之位置為:
: (a) 472 (b) 473 (c) 482 (d) 483
: ans: c
: 要怎麼計算阿?
一個struct的記憶體配置
記憶體位置
0~1 int id;
2~21 char name[20];
22~23 int age;
24 char sex;
而一個struct佔26byte
注意 並非25 因為要對齊 word
student[10]起始位置 = 200 + 10*26 = 460
而 age 距離struct開始22byte
所以 student[10].age 在 460 + 22 = 482
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.75.25