I want to allocate a memory to an array of pointers in struct, but I receive the following error:
expression must be a modifiable lvalue
Here's struct code:
typedef struct {
int id;
char *entity[];
}entity;
Here's memory allocation in main function:
entity s;
s.entity= malloc(30 * sizeof(char *));
IDE underlines s.entity and pops the error I mentioned.
Please, help me out to solve this issue.
CodePudding user response:
Your structure does not have a member called entity
, only id
and set
.
You apparently want to allocate the whole structure. This type of struct member called flexible array member is useful if you want to allocate the whole structure in one malloc
.
entity *s;
s = malloc(sizeof(*s) 30 * sizeof(s -> set[0]));
This kind of struct members are very useful as you can realloc
or free
them in a single call.
Increase the size of the set
array to 50
entity *tmp = realloc(s, sizeof(*s) 50 * sizeof(s -> set[0]));
if(tmp) s = tmp;
CodePudding user response:
Thats how you would allocate the pointers:
typedef struct {
int id;
char **set;
}entity;
int how_many_pointers = 30;
entity s;
s.set= malloc(how_many_pointers * sizeof(char *));
And for each pointer you would have to allocate the space for the corresponding string:
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'
}