繁体   English   中英

使用malloc在struct中设置指针数组的问题

[英]Problem with setting the array of pointers in the struct using malloc

我想为 struct 中的指针数组分配内存,但收到以下错误:

表达式必须是可修改的左值

这是结构代码:

typedef struct {
    int id;
    char *entity[];
}entity;

这是 main 函数中的内存分配:

entity s;
s.entity= malloc(30 * sizeof(char *));

IDE 在 s.entity 下划线并弹出我提到的错误。

请帮我解决这个问题。

您的结构没有名为entity的成员,只有idset

您显然想分配整个结构。 如果您想在一个malloc分配整个结构,这种称为灵活数组成员的结构成员非常有用。

entity *s;
s = malloc(sizeof(*s) + 30 * sizeof(s -> set[0]));

这种结构成员非常有用,因为您可以在一次调用中重新reallocfree它们。

set数组的大小增加到50

entity *tmp = realloc(s, sizeof(*s) + 50 * sizeof(s -> set[0]));
if(tmp) s = tmp;

这就是您分配指针的方式:

typedef struct {
    int id;
    char **set;
}entity;

int how_many_pointers = 30;
entity s;
s.set= malloc(how_many_pointers * sizeof(char *));

对于每个指针,您必须为相应的字符串分配空间:

int i, string_size;

for(i = 0; i < how_many_pointers; i++)
{
    printf("How many chars should have string number %d ?", i + 1);
    scanf("%d", &string_size);
    s.set[i] = malloc((string_size + 1) * sizeof(char)); // string + 1 due to space for '\0'
}

暂无
暂无

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

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