c - 使用复合文字来初始化 malloc 的缓冲区,

标签 c struct initialization malloc

有没有更简单的写法:

rver_t *buf = malloc(sizeof(rver_t));
rver_t tmp = (rver_t) {.op=OP_RVER, .protocol_version=1};
memcpy(buf, tmp, sizeof(rver_t));

用结构初始化 malloc 缓冲区?

注意:typedef 发生在 header 中:

#define OP_RVER 1
typedef struct rver_s {
    uint32_t op;
    uint32_t protocol_version;
} rver_t;

最佳答案

您可以输入:

buf -> op = OP_EVER;
buf -> protocol_version = 1;

关于c - 使用复合文字来初始化 malloc 的缓冲区,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14749968/

相关文章:

c - 主要返回后的段错误

非阻塞慢速采样传感器驱动程序的正确接口(interface)

c - 以两种方式实现快速排序算法但只接受一种?

c++ - std::set< struct > 按 struct c++ 中的属性值排序

r - nls 中的错误 - 迭代次数超过最大值

arrays - 缺少对数组常量的支持的解决方法?

c - 简单的 Bash-C 通信

go - 是否可以在 golang 中使用批量赋值?

c++ - Struct 中具有多个标记名称的构造函数 (C++)

c++ - 在结构中的数组中初始化结构中的数组时出现问题