在结构体中初始化数组 - C?

发布于 2024-09-28 20:29:55 字数 400 浏览 3 评论 0原文

似乎存在内存分配问题,并认为这是因为在我的结构中,有一个指向另一个结构的数组的指针。但是,我没有初始化这个数组,也不知道如何初始化:

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;
}

希望这是有道理的,你可以提供帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

场罚期间 2024-10-05 20:29:55

您将需要再次调用 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;
}

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;
}
<逆流佳人身旁 2024-10-05 20:29:55
bzero(tmp, sizeof(*tmp));

只是将结构列表的内容清零。如果那是你想要的。

bzero(tmp, sizeof(*tmp));

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文