Soumyajit Roy
Soumyajit Roy

Reputation: 463

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. But the output of the program is "" string. So nothing is getting copied to 'buffer'. Am I missing anything??

Upvotes: 0

Views: 3228

Answers (6)

alexbuisson
alexbuisson

Reputation: 8469

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";

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129364

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;

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

It's "" because int iPacket_number is probably laid out in memory as:

0x00 0x00 0x00 0x0a

which is an empty string (nul-terminator in the first character).

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.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You can't print an integer as text, because it's not text.

Upvotes: 0

icabod
icabod

Reputation: 7074

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). For example for a 4-byte 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.

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182761

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.

Upvotes: 3

Related Questions