简体   繁体   English

如何将结构内容复制到另一个数组结构

[英]how to copy struct contents to another array struct

I have this c++ struct 我有这个C ++结构

struct PACKET
{
    BOOL isTCPPacket;
    BOOL isUDPPacket;
    BOOL isICMPPacket;
    BOOL isIGMPPacket;
    BOOL isARPPacket;
    BOOL isIPPacket;

    struct PETHER_HEADER
    {
        string  DestinationHost;
        string  SourceHost;
        struct PROTOCOL_TYPE
        {
            string  Name;
            WORD    Identifier;
        } ProtocolType;
    } EthernetHeader;
};

and i have 我有

PACKET* Packet;
PACKET* Packets[6];

how can i copy contents of Packet into Packets[3] for example, knowing that the Packet contents will vary for each array in Packets[INDEX] 例如,我知道如何将Packet的内容复制到Packets [3]中,因为知道Packet的内容对于Packets中的每个阵列都会有所不同[INDEX]

I have tried memcpy as 我尝试过memcpy作为

memcpy((void*)&Packets[i],(void*)&Packet,sizeof(PACKET));

with no luck 没有运气

How about Packets[3] = Packet; Packets[3] = Packet;怎么样Packets[3] = Packet; ? This does exactly what you asked (copies the content of Packet , which is a pointer, into Packets[3] ). 这恰好满足您的要求(将作为指针的Packet的内容复制到Packets[3] )。

If you want to copy the values, you can use assignment as well: *(Packets[3]) = *Packet; 如果要复制值,也可以使用赋值: *(Packets[3]) = *Packet; , assuming the pointers are valid. ,假设指针有效。 The compiler generated assignment operator for PACKET should work just fine. 编译器为PACKET生成的赋值运算符应该可以正常工作。

I'd avoid memcpy in this case, since some of the members are std::string - you're bound to run into trouble. 在这种情况下,我会避免使用memcpy ,因为某些成员是std::string -您肯定会遇到麻烦。

Hope Packet contains valid object. 希望数据包包含有效对象。 Also Packets[i] point to allocated objects. Packets [i]也指向分配的对象。

Do this: Packet[i] = Packet; 执行以下操作:Packet [i] =数据包;

As string objects store pointers in their objects and can only be duplicated using assignment operator. 由于字符串对象将指针存储在其对象中,因此只能使用赋值运算符进行复制。

Ah! 啊! Just one thing: 就一件事:

PACKET* Packets[6];

is different than: 不同于:

PACKET (*Packets)[6];

Former is an array of pointer (ie 6-pointers), but latter is a pointer to hold address-of a PACKET[6] array! 前一个是指针数组(即6指针),而后一个是保存PACKET[6]数组地址的指针!

In either case, you must allocate memory for your Packet variable. 无论哪种情况,都必须为Packet变量分配内存。 memcpy or assignment will not work, unless some heap or stack memory is allocated. 除非分配了一些堆或堆栈内存,否则memcpy或分配将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM