[問題] 轉型問題 是否符合標準?

看板C_and_CPP (C/C++)作者 (JOMI)時間5年前 (2020/03/17 12:18), 5年前編輯推噓0(001)
留言1則, 1人參與, 5年前最新討論串1/1
請教各位 我有以下需求 我有一塊buffer, 我想要取其中任意起始位址後面若干byte來看他的數值是不是我要的 以下是簡單的我大概會用的寫法 template<class T> T* Read(char* buf, int position) { return reinterpret_cast<T*>(buf + position); } int main() { constexpr unsigned short TEST1 = 0x0403; constexpr unsigned int TEST2 = 0x04030201; char buf[] = {0x01, 0x02, 0x03, 0x04}; if ((*Read<unsigned short>(buf, 2)) == TEST1) { cout<<"bingo"<<endl; } if ((*Read<unsigned int>(buf, 0)) == TEST2) { cout<<"bingo2"<<endl; } 我的問題是 因為牽扯到轉型, 我實在沒有很有把握說這種寫法是合法的 感覺很容易就是undefined behavior.... 可否請各位指教 該如何做 才是對的 隱約有個alignment的問題覺得這寫法不太對 template<class TargetType> void Read2(char* buf, int position, TargetType& t) { memcpy_s(&t, sizeof(TargetType), buf + position, sizeof(TargetType)); } 如果是這樣寫會不會比較正確 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.10.158.16 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1584418725.A.560.html ※ 編輯: lovejomi (39.10.158.16 臺灣), 03/17/2020 13:41:04

03/20 02:52, 5年前 , 1F
你是不是在找 memcmp
03/20 02:52, 1F
文章代碼(AID): #1US4-bLW (C_and_CPP)
文章代碼(AID): #1US4-bLW (C_and_CPP)