结构铸造时丢失信息

时间:2016-03-03 16:06:39

标签: c++ data-structures struct casting

我通过将结构类型转换为整数来传递结构。 在输出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;
}

1 个答案:

答案 0 :(得分:1)

C ++中*(UINT32 *)&Book1的行为是 undefined 。这是因为类型无关。在指针大于32位的64位平台上,它会特别脆弱。

可以逃避void*的强制转换,但这并不是真正应该用C ++完成的事情。

为什么不在printBook books内移动struct ?您可以在C ++中执行此操作:C ++ struct可以容纳成员函数以及成员数据。 (在C ++中不需要围绕typedef的C风格的struct习语。

最后,#define UINT16 int后跟typedef unsigned int UINT32;只是奇怪的。如果编译器支持,请考虑使用标准的固定大小(例如std::uint32_t)。

相关问题