Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with setting the array of pointers in the struct using malloc

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading