将包含位字段和动态数据的结构复制到 Char 数组缓冲区中
Copying struct with bitfields & dynamic data into a Char array buffer
我具有以下
的结构struct Struct {
int length; //dynamicTest length
unsigned int b: 1;
unsigned int a: 1;
unsigned int padding: 10;
int* dynamicTest;
int flag;
}
我想将其复制到char阵列缓冲区(以发送插座)。我很好奇我会怎么做。
确切地说,您可以使用 memcpy
,例如:
#include <string.h>
/* ... */
Struct s = /*... */;
char buf[1024]
memcpy(buf, &s, sizeof(s));
/* now [buf, buf + sizeof(s)) holds the needed data */
另外,您可以完全避免复制 view struct作为char数组的实例(由于计算机内存中的所有内容都是字节的顺序,因此此方法有效)。
Struct s = /* ... */;
const char* buf = (char*)(&s);
/* now [buf, buf + sizeof(s)) holds the needed data */
如果要通过网络发送它,则需要照顾字节订单,INT大小和许多其他详细信息。
复制位字段没有任何问题,但是对于动态字段(例如您的char*
),这种天真的方法无法使用。与其他任何类型一起使用的更通用的解决方案是序列化。
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 使用动态分配将 char* 复制到另一个字符**
- 如何将 cv::Mat & Img 复制到未签名的 char* img?opencv
- 我可以使用istream_iterator将<char>一些 istream 内容复制到 std::string 中吗?
- char 和 char& 之间是否存在相对复制开销差异?
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- 如何将const char*复制到c 中的uint8_t []
- char 数组在上次迭代时复制整个单词而不是单个字母
- 将 char[ ][ ] 的地址复制到 C 字符串
- 将包含位字段和动态数据的结构复制到 Char 数组缓冲区中
- C 2D char阵列有时会在随机位置复制数据
- C 使用指针复制char*
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较
- 我可以在不复制的情况下将 std::vector 重新解释<char>为 std::vector<无符号字符>吗?
- C - 从const char*复制到字符串
- 如何将足够的数据从文本文件分配到char*中,然后将其复制到内存C 中
- 如何将STD :: String的值复制到Char数组类型的结构成员
- 正在从方法范围复制char*
- c++中使用指针复制char数组的奇怪行为
- 在指定位置复制char*到std::string,不分配新对象