我预测char数组类型值只能投射指针类型

I predict Char array type value could cast pointer type only

本文关键字:类型 指针 char 数组      更新时间:2023-10-16

我预测char值类型只能投射指针类型。我是吗?

struct1和struct2之间的这些区别是什么?

此外,有人说这可能是错误的。

struct UdpReceive ReceiverA;    
UdpReceive ReceiverB; // <= It's supposed to be an Error.

但是我无法在C 中实现这一目标,然后编译成功。此错误仅在C中发生吗?谢谢。

int main()
{
    //It will be assumed containd Byte data of UDP.
    unsigned char ReceivedData[128];
    //Struct pt1
    struct  UdpReceive {
        char name[20];
        int age;
        double hegiht;
    };
    UdpReceive ReceiveBuffer;
    UdpReceive* pReceiveBuffer;
    //Struct pt2
    typedef struct{
        char name[20];
        int age;
        double hegiht;
    }V2SUdpReceive, *V2SUdpReceive;
    V2SUdpReceive V2ReceiveBuffer;
    V2SUdpReceive* pV2ReceiveBuffer;

    pReceiveBuffer = (UdpReceive*)ReceivedData; 
    ReceiveBuffer = (UdpReceive)ReceivedData;// <= it's not pointer type that is reason why Error.
    pV2ReceiveBuffer = (V2SUdpReceive*)ReceivedData;
    V2ReceiveBuffer = (V2SUdpReceive)ReceivedData;// <= it's not pointer type that is reason why Error.
}

在C中您可以施放一个炭指针。

在C 中,您也可以做到,但您不应该这样做。虽然它可能起作用。但是C 不能保证您在内部表示如何表示结构的数据。

您的问题称为序列化/避免。您有结构,您想将其内容发送给另一方。但是对方可能对这种结构有不同的内部内存表示形式。并且数据的正确接收将失败。

如果您想在没有生产代码中自己做,请尝试使用铸件,如果它有效,请使用它。

也许更好:创建一些用于序列化/进行序列化的功能,也许覆盖插入器>>和提取器操作员&lt;&lt;。或者,使用通用的序列化框架,您可以在网上找到。