简体   繁体   English

如何通过指针读取 memcpy 结构结果

[英]how to read memcpy struct result via a pointer

I want to copy struct content in memory via char* pc the print it back but hear I have exception (reading violation)我想通过char* pc复制内存中的结构内容并将其打印回来,但听说我有异常(读取违规)

struct af {
        bool a;
        uint8_t b;
        uint16_t c;
    };

int main() {

        af t;
        t.a = true;
        t.b = 3;
        t.c = 20;

        char* pc = nullptr;

        memcpy(&pc, &t, sizeof(t));

        std::cout << "msg is " << pc << std::endl; // here the exception

        return 0;
    }

then I want to recover data from memory to another structure of same type I did af* tt = (af*)(pc);然后我想将数据从内存恢复到我所做的相同类型的另一个结构af* tt = (af*)(pc); then tried to access to tt->a but always exception然后尝试访问tt->a但总是异常

You need to allocate memory before you can copy something into it.您需要先分配内存,然后才能将某些内容复制到其中。 Also, pc is already the pointer, you need not take the address of it again.另外, pc已经是指针了,不需要再取它的地址了。 Moreover, the byte representation is very likely to contain non-printable characters.此外,字节表示很可能包含不可打印的字符。 To see the actual effect the following copies from the buffer back to an af and prints its members (note that a cast is needed to prevent std::cout to interpret the uint8_t as a character):要查看实际效果,请将以下从缓冲区复制回af并打印其成员(请注意,需要进行std::cout转换以防止std::coutuint8_t解释为字符):

#include <iostream>
#include <cstring>

struct af {
        bool a;
        uint8_t b;
        uint16_t c;
    };

int main() {
    af t;
    t.a = true;
    t.b = 3;
    t.c = 20;

    char pc[sizeof(af)];

    std::memcpy(pc, &t, sizeof(t)); // array pc decays to pointer to first element

    for (int i=0;i<sizeof(af); ++i){
        std::cout << i << " " << pc[i] << "\n";
    }
    af t2;
    std::memcpy(&t2, pc,sizeof(t));
    std::cout << t2.a << " " << static_cast<unsigned>(t2.b) << " " << t2.c;

}

Output :输出

0 
1 
2 
3 
1 3 20

Note that I replaced the output of pc with a loop that prints individual characters, because the binary representation might contain null terminators and pc is not a null terminated string.请注意,我用打印单个字符的循环替换了pc的输出,因为二进制表示可能包含空终止符,而pc不是空终止字符串。 If you want it to be a null-terminated string, it must be of size sizeof(af) +1 and have a terminating '\\0' .如果你希望它是一个以空字符结尾的字符串,它的大小必须是sizeof(af) +1并且有一个终止'\\0'

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

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