我通过将它作为整数进行类型转换来传递一个结构体。 在输出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” 不会是你所期望的某些操作系统是什么。 –