简体   繁体   English

使用memcpy尝试将一个结构复制到char []缓冲区中

[英]Using memcpy trying to copy one struct into a char[] buffer

#define ECHOMAX 100

struct tDataPacket
{
    int iPacket_number;
    char sData[ECHOMAX];
};

int main () {
    tDataPacket packet;
    packet.iPacket_number=10;
    strcpy(packet.sData,"Hello world");
    char buffer[sizeof(tDataPacket)];

    memcpy(buffer,&packet.iPacket_number,sizeof(int));
    memcpy(buffer+sizeof(int),packet.sData,ECHOMAX);

    std::cout<<"Buffer = "<<buffer<<"END";
  return 0;
}

In the above code I am trying to pack my structure in a char[] buffer so that I can send it to a UDP socket. 在上面的代码中,我试图将结构打包在char []缓冲区中,以便可以将其发送到UDP套接字。 But the output of the program is "" string. 但是程序的输出是“”字符串。 So nothing is getting copied to 'buffer'. 因此,没有任何内容被复制到“缓冲区”。 Am I missing anything?? 我错过了什么吗?

When you copy the int, at least one of the first "n" characters of the buffer will be zero (where "n" is the size of an int on your platform). 复制int时,缓冲区的前“ n”个字符中至少有一个为零(其中“ n”是平台上int的大小)。 For example for a 4-byte int: 例如对于一个4字节的int:

x00 x00 x00 x0a   or   x0a x00 x00 x00

Depending on the endianness of your processor. 取决于处理器的字节序。

Printing out the zero will have the effect of terminating the output string. 打印出零将具有终止输出字符串的作用。

You have no code to sensibly print the contents of the buffer, so you are expecting this to work by magic. 您没有代码可以明智地打印缓冲区的内容,因此您希望它可以神奇地工作。 The stream's operator << function expects a pointer to a C-style string, which the buffer isn't. 流的operator <<函数需要一个指向C样式字符串的指针,而缓冲区则不是。

It's "" because int iPacket_number is probably laid out in memory as: int iPacket_number""是因为int iPacket_number可能在内存中的布局为:

0x00 0x00 0x00 0x0a

which is an empty string ( nul -terminator in the first character). 这是一个空字符串(第一个字符为nul终止符)。

Firstly you probably want some sort of marshalling so that the on-the-wire representation is well established and portable (think endian differences between platforms). 首先,您可能希望进行某种编组,以便建立在线表示并使其易于移植(请考虑平台之间的字节序差异)。

Secondly you shouldn't need to "print" the resulting string; 其次,您不需要“打印”结果字符串。 it makes no sense. 这个不成立。

Thirdly you want unsigned char , not (signed) char . 第三,您需要unsigned char ,而不是(signed) char

您不能将整数打印为文本,因为它不是文本。

You will need to do a loop (or something like that) to print the actual contents of the buffer: 您将需要执行循环(或类似操作)以打印缓冲区的实际内容:

 std::cout << "Buffer=";
 for(size_t i = 0; i < sizeof(tDataPacket); i++)
 {
    std::cout << hex << (unsigned int)buffer[i] << " ";
    if ((i & 0xf) == 0xf) std::cout << endl;   // Newline every 16. 
 }
 std::cout << "END" << endl;

You can do this but it's not really relevant to display binary data like that: 您可以执行此操作,但显示这样的二进制数据并不真正相关:

std::cout<<"Buffer = "; for each (auto c in buffer)
{
    std::cout<< c; 
} 
std::cout <<"END";

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

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