简体   繁体   中英

Initializing array inside struct - C?

Seem to have a memory allocation problem and think it's because in my struct, there is a pointer to an array of another struct. However, I'm not initializing this array and not sure how:

typedef struct listitem {
    struct listitem *next;
    Entry *entry;
} ListItem;

typedef struct list {
    ListItem *table[100];
} List;

List *initialize(void)
{
    List *tmp;

    if ((tmp = (List *)malloc(sizeof(List))) == NULL)
        return NULL;
    return tmp;
}

Hope that makes sense and you could help!

You will need to call malloc again.

typedef struct listitem {
    struct listitem *next;
    Entry *entry;
} ListItem;

typedef struct list {
    ListItem *table[100];
} List;

List *initialize(void)
{
    List *tmp;

    if (!(tmp = (List *)malloc(sizeof(List))))
        return NULL;
    for(int i = 0; i < 100; i++) {
        tmp->table[i] = (ListItem*)malloc(sizeof(ListItem));
    }
    return tmp;
}
bzero(tmp, sizeof(*tmp));

just zeroes the contents of your struct list. If that is what you want.

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