使用结构初始化语法上堆结构 [英] Use of struct initialization syntax for on-heap struct

查看:112
本文介绍了使用结构初始化语法上堆结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种简单的结构我想初始化堆,并返回作为函数的指针。

I have this simple structure I want to initialize on the heap and return as a pointer in a function.

struct entry {
    const char* const key; // We don't want the key modified in any way
    const void* data;      // But the pointer to data can change
    struct entry* next;
};

有一个问题,我不能释放calloc 它和一个初始成员之一,因为是一个常量指针。我在什么地方找到这个语法如下:

There is one problem, I cannot calloc it and initialize members one by one because key is a const pointer. I found somewhere this syntax that works:

struct entry* entry = calloc(1, sizeof(struct entry));
*entry = (struct entry) { .key = key, .data = data, .next = NULL };

但我不知道是怎么回事吧:它创建一个匿名结构,然后将其复制到 *项生活的地方?是安全使用或者我应该preFER创建本地结构,然后与的memcpy 复制到正确的位置?

But I don't know what is going on with it: does it create an "anonymous" struct that is then copied to the place where *entry lives? Is that safe to use or should I prefer creating a local struct that is then copied with memcpy to the right location?

推荐答案

分配你presented是不正确的,不应该编译。

The assignment you presented is not correct and should not compile.

为const成员初始化分配的结构的正确方法是分配一些内存,创建一个临时结构条目对象,然后用memcpy的对象复制到分配的内存:

The correct way of initializing an allocated struct with const members is to allocate some memory, create a temporary struct entry object, and then use memcpy to copy the object to the allocated memory:

void* mem = malloc( sizeof( struct entry ) );
struct entry temp = { key , data , NULL };
memcpy( mem , &temp , sizeof( temp ) );
struct entry* e = mem;

这篇关于使用结构初始化语法上堆结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆