使用 malloc 在结构中设置指针数组的问题
Problem with setting the array of pointers in the struct using malloc
我想为结构中的指针数组分配内存,但收到以下错误:
expression must be a modifiable lvalue
结构代码如下:
typedef struct {
int id;
char *entity[];
}entity;
下面是main函数中的内存分配:
entity s;
s.entity= malloc(30 * sizeof(char *));
IDE 下划线 s.entity 并弹出我提到的错误。
请帮我解决这个问题。
您的结构没有名为 entity
的成员,只有 id
和 set
.
您显然想分配整个结构。如果您想在一个 malloc
.
中分配整个结构,这种称为 灵活数组成员 的结构成员很有用
entity *s;
s = malloc(sizeof(*s) + 30 * sizeof(s -> set[0]));
这种结构成员非常有用,因为您可以在一次调用中 realloc
或 free
它们。
将 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 *));
并且对于每个指针,您必须为相应的字符串分配 space:
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 '[=11=]'
}
我想为结构中的指针数组分配内存,但收到以下错误:
expression must be a modifiable lvalue
结构代码如下:
typedef struct {
int id;
char *entity[];
}entity;
下面是main函数中的内存分配:
entity s;
s.entity= malloc(30 * sizeof(char *));
IDE 下划线 s.entity 并弹出我提到的错误。
请帮我解决这个问题。
您的结构没有名为 entity
的成员,只有 id
和 set
.
您显然想分配整个结构。如果您想在一个 malloc
.
entity *s;
s = malloc(sizeof(*s) + 30 * sizeof(s -> set[0]));
这种结构成员非常有用,因为您可以在一次调用中 realloc
或 free
它们。
将 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 *));
并且对于每个指针,您必须为相应的字符串分配 space:
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 '[=11=]'
}