简体   繁体   中英

memcpy in C++ doesn't copy u_int32_t to unsigned char*

I'm with a problem when using memcpy function.

I need to create an array of unsigned char with three parts: id, size of data array, data array. But I couldn't do nor the first part yet.

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>

int main() {    
    u_int32_t OID;
    unsigned char *serialized;
    
    OID = (u_int32_t)5;
    
    serialized = new unsigned char[sizeof(u_int32_t)];
    
    memcpy(serialized, &OID, sizeof(u_int32_t));
    
    std::cout << "After inserting OID: <" << serialized << ">\n";
    
    memcpy(serialized, "test", sizeof(u_int32_t));
    
    std::cout << "After inserting \'test\': <" << serialized << ">\n";

}

The output this code generates is:

    After inserting OID: <> 
    After inserting 'test': <test>

I can't understand why, in the first case, memcpy doesn't copy OID to serialized and in the second case it copies the string test correctly.

It would be great if you could help me.

Thank you in advance.

Solution

I was trying to get number 5 when printing serialized . But it is not correct. The most adequate is to do something like this:

u_int32_t answer;
memcpy(&answer, serialized, sizeof(u_int32_t));
std::cout << "Answer: <" << answer << ">\n";

Thanks for answers and comments!

5 in ASCII is not printable since it's a control character. ASCII Table

You can try below and it will print a as expected.

OID = (u_int32_t)'a';

Solution

I was trying to get number 5 when printing serialized . But it is not correct. The most adequate is to do something like this:

u_int32_t answer;
memcpy(&answer, serialized, sizeof(u_int32_t));
std::cout << "Answer: <" << answer << ">\n";

Thanks for answers and comments!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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