Re: [問題] 請問struct的使用

看板C_and_CPP作者 (朴髮箍)時間14年前 (2011/04/27 23:20), 編輯推噓5(500)
留言5則, 5人參與, 最新討論串2/2 (看更多)
※ 引述《liptonbin (wind)》之銘言: : 今天面試考了一題,如下 : 請宣告一個struct 且 賦與其變數值 : offset size name format data : 0x000 1 USB_Field Integer 0010 : 0x001 2 USB_Field_2 Integer 0020 : 0x005 4 USB_Field_3 string 0025 : 0x007 2 USB_Field_4 Integer 0010 ■: byte USB_Field USB_Field_2 USB_Field_3 USB_Field_4 只考慮所佔大小的話, 記憶體佈局大概是這樣: 0 1 2 3 4 5 6 7 8 (位移) ■■■■■■■■ 但是把位移加進來的話: 0 1 2 3 4 5 6 7 8 (位移) ■■ ■■■■ ■■ 記憶體重疊的話, 表示需要搭配 union 來實作: #include <stdint.h> // 請愛用能保證大小的型態 struct USB { int8_t USB_Field; int16_t USB_Field_2; union { struct { int16_t unused; char USB_Field_3[ 4 ]; }third; struct { int32_t unused; int16_t USB_Field_4; }fourth; }common; } __attribute__((packed));// 注意這行, 每個編譯器需要的 // 指令不太一樣, 告訴它不要為 // 了加速在每個成員間加料 : 我答案寫成底下,不曉得這樣對不對?麻煩高手指正一下,謝謝 : 另外format是integer 而size是1,我用char去宣告,不曉得這樣對不對?? : struct USB{ : char USB_Field; : short USB_Field_2; : int USB_Field_3; : short USB_Field_4; : }; : USB *p; : p->USB_Field=0010; : p->USB_Field_2=0020; : p->USB_Field_3=0025; : p->USB_Field_4=0010; struct USB usb; usb.USB_Field = 0010; usb.USB_Field_2 = 0020; strcpy( usb.common.third.USB_Field_3, "025" ); usb.common.fourth.USB_Field_4 = 0010; 我也覺得是題目中成員大小給錯...囧 -- ▂▂ ▄▂ T.T.L Listen 2 http://ppt.cc/jIUk ˇ ˇˇ ˇ 說什麼結束 ▃▃ http://ppt.cc/zQtB ψ髮箍 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.121.197.115 ※ 編輯: loveme00835 來自: 140.121.197.115 (04/28 00:59)

04/28 07:41, , 1F
版主根本就是把BBS當成小畫家!!XD
04/28 07:41, 1F

04/28 08:31, , 2F
推版主招牌圖解!
04/28 08:31, 2F

04/28 09:43, , 3F
上色好漂亮啊 >///<
04/28 09:43, 3F

04/28 12:10, , 4F
幫推 感謝大大分享
04/28 12:10, 4F

04/29 01:00, , 5F
推!!
04/29 01:00, 5F
文章代碼(AID): #1Dk3Gsbw (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Dk3Gsbw (C_and_CPP)