简体   繁体   中英

non-static initialization of a flexible array member

I'm trying to populate a struct member with an array created at runtime and get the following error:

error: non-static initialization of a flexible array member
             .entries = entries
                        ^

I have isolated the problem and reproduced it in simpler code to make it clearer:

#include <stdlib.h>

typedef struct entry {
    char *title;
    int id;
} Entry;

typedef struct collection {
    size_t size;
    Entry entries[];
} Collection;

// This function signature may not be changed
void populate(int n, Collection *result){

    Entry entries[n];

    for (int i = 0; i < n; ++i) {
        Entry entry = {
                .title = "Title",
                .id = i
        };

        entries[i] = entry;
    }

    Collection collection = {
            .size = n,
            .entries = entries
    };

    result = &collection;
}

How can I fix this?

Actually, initialising a struct with a flexible array member is not straight forward; You will have to allocate a collection item with enough space for the entries you'd like to copy in later. So you could write something like the following:

Collection *coll = malloc(sizeof(Collection)+n*sizeof(Entry));
coll->size = n;
memcpy (coll->entries, entries, n*sizeof(Entry));

I see no other way than using such a "hand-written" malloc .

Note however, that if memory allocation is expected to be done in function populate , the signature of function populate cannot remain as is, because it would not allow to "return" or set a pointer to a newly allocated Collection -object. In this case, the signature would have to be changed either into void populate(int n, Collection **result) or into Collection *populate(int n) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM