将结构转换为字符*并返回
converting struct to char* and back
我正在尝试将我的结构转换为字符*,然后再转换为结构。但我想我错过了一些东西。一旦它返回到结构,结构只有一个属性是正确的。其余的都是错的。这是我的代码。
#include <iostream>
using namespace std;
struct INFO {
unsigned char a;
int b;
int c;
char g[121];
}inf;
int main () {
char frame[128];
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
sprintf(frame,(char*)&test1);
INFO test2 = INFO();
memcpy((char*)&test2, frame, sizeof(frame)); //shouldn't test2 have test1 values?
cout << test2.a<<"n";
cout << test2.b<<"n";
cout << test2.c<<"n";
cout << test2.g<<"n";
getchar();
return 0;
}
输出:
y
-858993460
-858993460
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
只有test2.a是正确的。是我错误地将其转换为字符*,还是我将其转换回来的方式?谢谢
此代码存在一些问题,但导致问题的问题是使用 sprintf
将二进制数据从结构复制到字符数组:如果结构数据中的任何位置存在 NUL 字节,则复制将停止。在这种情况下,结构数据中紧跟在第一个成员之后,嵌入在第二个成员中或由于填充而存在 NUL 字符,因此仅完全复制第一个成员。
使用 memcpy
而不是 sprintf
。
// sprintf(frame,(char*)&test1); <-- wrong
memcpy(frame, &test1, sizeof(frame));
INFO test2 = INFO();
memcpy(&test2, frame, sizeof(frame));
另一个问题是,由于填充和对齐,INFO结构的大小可能不是128,因此无法完全复制到frame
。使用 sizeof
运算符查找大小。
char frame[sizeof(INFO)]; // Let compiler decide size of frame
INFO test1 = INFO();
test1.a='y';
test1.b=4000;
test1.c=9000;
strcpy(test1.g, "Goodbye World");
memcpy(frame, &test1, sizeof(INFO)); // copy memory and not string
相关文章:
- std::stringstream 返回字符 *
- 使用字符串 c_str() 返回字符*
- 从函数返回字符*
- Flex/Bison从C 中的扫描仪返回字符令牌
- 为什么getServicedisplaynamew()和getServicedisplaynamea()返回字符中不同所
- std::string::d ata() 不会返回字符*
- 在 c++ 中返回'/n'字符
- C 如何编写返回字符指针的功能
- 从函数返回字符*不起作用
- 为什么我的函数在应该返回字符时返回垃圾
- C++ Wrting 一个函数,该函数从名为 line_of_input 的字符串中返回字符"a"、"e"、"i"的出现次数
- 删除返回字符*的位置
- 通过赋值运算符返回字符数组
- 字符到 ASCII 代码转换并返回字符
- 尝试返回字符数组
- Arduino,返回字符数组的函数
- C++返回字符指针并打印
- 使用 std::cin >>时可以丢弃返回字符吗?
- 如何从课堂上返回字符*
- 如何使用模板返回字符值