Cranium Cranium - 1 year ago 80
C Question

Use of struct initialization syntax for on-heap struct

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;

There is one problem, I cannot
it and initialize members one by one because
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 };

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
lives? Is that safe to use or should I prefer creating a local struct that is then copied with
to the right location?

Answer Source

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

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download