简体   繁体   English

C++ 中的 memcpy 不会将 u_int32_t 复制到 unsigned char*

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

I'm with a problem when using memcpy function.我在使用memcpy function 时遇到问题。

I need to create an array of unsigned char with three parts: id, size of data array, data array.我需要创建一个包含三个部分的unsigned char数组:id、数据数组的大小、数据数组。 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:此代码生成的 output 是:

    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.我不明白为什么,在第一种情况下, memcpy不会将OID复制到serialized ,而在第二种情况下,它会正确复制字符串test

It would be great if you could help me.如果你能帮助我,那就太好了。

Thank you in advance.先感谢您。

Solution解决方案

I was trying to get number 5 when printing serialized .我在打印serialized时试图获得5号。 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 中的5不可打印,因为它是控制字符。 ASCII Table ASCII 表

You can try below and it will print a as expected.您可以在下面尝试,它会a预期打印。

OID = (u_int32_t)'a';

Solution解决方案

I was trying to get number 5 when printing serialized .我在打印serialized时试图获得5号。 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!感谢您的回答和评论!

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

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