1

I have searched so much but yet hadn't found any good solution for c. I want to initialize an array with dynamic size. The solution I saw so far was a linked list but it seems it doesn't meet my requirements.

The code I had tested so far is as below

typedef struct 
{
    const unsigned char widgetCount;
    unsigned char index;
    lv_obj_t * radiobtnVIEW[widgetCount];
}AssetVIEW;

and then to initialize widgetCount

AssetVIEW View={4};

The error I get is

error: 'widgetCount' undeclared here (not in a function)

Your help is appreciated by this newbie.

V.Ajall
  • 49
  • 1
  • 6
  • 4
    What you seem to be looking for is a [*flexible array member*](https://en.wikipedia.org/wiki/Flexible_array_member). Or plain pointers. Either way, you can't solve it without dynamic allocation (i.e. `malloc` and friends). – Some programmer dude Sep 22 '21 at 06:26
  • 2
    Does this answer your question? [What is a flexible array member in a struct?](https://stackoverflow.com/questions/68769314/what-is-a-flexible-array-member-in-a-struct) – kaylum Sep 22 '21 at 06:29
  • @kaylum the compiler will throw this error error: invalid application of 'sizeof' to incomplete type 'struct AssetVIEW' – V.Ajall Sep 22 '21 at 06:41
  • 1
    When you do what? We can't see your code so you need to be specific. Provide an [mre] in a new question. – kaylum Sep 22 '21 at 06:44
  • If you get new errors, then please post new questions. – Some programmer dude Sep 22 '21 at 06:45

1 Answers1

0

You cannot, in C, refer to other fields within the struct while it's being declared. This is what the error message refers to. As noted, you can use a pointer or a flexible array member (fam):

lv_obj_t **radiobtnVIEW;
lv_obj_t *radiobtnVIEW[];

For fam, you dynamically allocate memory for said field:

size_t n = 4;
AssetVIEW *View = malloc(sizeof(*View) + n * sizeof(*View->radiobtnVIEW));
...
free(View);

Note that the const qualifier on widgetCount doesn't make sense as you cannot initialize it.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • So is it possible to embed the array size in the structure? By which I mean to set widgetCount and omit variable n. Is it possible in C++? – V.Ajall Sep 23 '21 at 12:09
  • You are embedding the size in the structure but you just cannot refer to that field while creating the instance. If you want you could malloc instance, set widgetCount, then realloc using widgetCount but not sure why you would want to. If you use a pointer instead of fam, then you just do it in sequence, first assign widgetCount, then allocate and set radiobtnVIEW using widgetCount. – Allan Wind Sep 24 '21 at 02:33
  • The reason is I am working on MCU on which I should keep track of RAM usage, so it's important to initialize arrays in struct with absolute size. On the other hand, it would be good to have a sample and have a template and use it with different sizes. Something like object-oriented programming, which was introduced in CPP. – V.Ajall Sep 29 '21 at 04:30