把结构体地址转化成unsigned char* 后,可以把得到的unsigned char* 复原成结构体吗 ,给出代码
时间: 2024-05-11 17:13:56 浏览: 151
可以通过强制类型转换将结构体地址转换为unsigned char*,然后再将unsigned char*转换回结构体。
以下是代码示例:
```c++
#include <iostream>
#include <cstring>
using namespace std;
struct Person {
char name[20];
int age;
float height;
};
int main() {
Person p1 = {"Alice", 25, 1.68f};
unsigned char* ptr = reinterpret_cast<unsigned char*>(&p1); // 将结构体地址转换为unsigned char*
// 打印unsigned char*中的每个字节
for (int i = 0; i < sizeof(Person); i++) {
cout << static_cast<int>(*(ptr + i)) << " ";
}
cout << endl;
// 将unsigned char*转换回结构体
Person p2;
memcpy(&p2, ptr, sizeof(Person));
cout << "Name: " << p2.name << endl;
cout << "Age: " << p2.age << endl;
cout << "Height: " << p2.height << endl;
return 0;
}
```
输出结果:
```
65 108 105 99 101 0 0 0 25 0 0 0 170 66 73 63
Name: Alice
Age: 25
Height: 1.68
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)