简体   繁体   English

在结构内部初始化数组-C?

[英]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. 您将需要再次调用malloc。

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. 如果那是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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