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.
CodePudding user response:
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[];
Then dynamically allocate memory for said field:
size_t n = 4;
AssetVIEW *View = malloc(sizeof(*View) n * sizeof(*View->radiobtnVIEW));
...
free(View);
In the fam case, the const
qualifier on widgetCount
doesn't make sense as you cannot initialize it.