我通過將它作爲整數進行類型轉換來傳遞一個結構體。 在輸出printBook(),我重新獲取套接字,通過類型化傳入的整數。結構鑄造時信息丟失
預期輸出: -
Book id : 11
Book no of copies : 2
Book id : 12
Book no of copies : 10
實際輸出
Book id : 11
Book no of copies : 0
Book id : 12
Book no of copies : 0
爲什麼我失去的部分數據? 這是摘錄。
#define UINT16 int
typedef unsigned int UINT32;
using namespace std;
#include <iostream>
#include <cstring>
using namespace std;
// this replicates my new Data structure
typedef struct books
{
UINT16 book_id;
UINT16 book_no_of_copies;
books() : book_id(0), book_no_of_copies(0) {}
} BOOKS;
void printBook(UINT32 book);
int main()
{
BOOKS Book1; // Declare Book1 of type BOOKS
BOOKS Book2; // Declare Book2 of type BOOKS
// book 1 specification
Book1.book_id = 11; // initialization
Book1.book_no_of_copies = 2;
// book 2 specification
Book2.book_id = 12; // initialization
Book2.book_no_of_copies = 10;
// pass struct as integer
// Print Book1 info
printBook(*(UINT32 *)&Book1);
// Print Book2 info
printBook(*(UINT32 *)&Book2);
getchar();
return 0;
}
void printBook(UINT32 book)
{
// re-convert integer to struct
BOOKS myBook = *(BOOKS *)& book;
cout << "Book id : " << myBook.book_id <<endl;
cout << "Book no of copies : " << myBook.book_no_of_copies <<endl;
}
'#define UINT16 int','typedef unsigned int UINT32;'什麼? int和unsigned int具有不同的大小? –
在我的Ubuntu 15.10(64位)操作系統, 「的sizeof(int)的」 報告4個字節,同爲 「的sizeof(uint32_t的)」,這樣你的 「的#define UINT16 INT」 不會是你所期望的某些操作系統是什麼。 –