0

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.

2
  • an array is not modifiable. What you want instead is char** set Commented Nov 14, 2021 at 13:07
  • 1
    The way you wrote this, you should basically use: entity *s = malloc(sizeof *s + 30 * sizeof *s->set); Commented Nov 14, 2021 at 13:10

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I am not one of the downvoters, but your first suggestion didn't work because set is a flexible array member. I guess you realised, since you edited your answer.
@Cheatah: What do you see wrong in the first version of the answer? It has malloc(sizeof(*s) + 30 * sizeof(s -> set[0]));, which is correct for allocating space for the structure plus 30 elements in the array member.
@EricPostpischil the very first one was wrong :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.