I have the STRUCT1 Structure declared as below
typedef struct struct1 {
short int nbr_fe;
[size_is(nbr_fe)] STRUCT2 ptr_fe[*];
} STRUCT1;
STRUCT2 is also another structure inside STRUCT1
and then I have a pointer declared to it as below
typedef [ptr] STRUCT1 * ptr;
And I have to allocate a memory to an array of STRUCT1 base on the nbrRequested And so far I have
STRUCT1 obj1;
memset((void*)&obj1, '\0' , sizeof(STRUCT1));
for(int i1=0;i1<(int)nbrRequested;i1++) {
STRUCT2 obj2;
memset((void*)&obj2, '\0' , sizeof(STRUCT2));
obj1.ptr_fe[i1] = obj2;
}
ptr ptr2;
ptr2 = &obj1;
but if the nbrRequested is greater than 500, the loop goes in infinite and the application hangs.
Is there any better way to allocate a memory without using for loop
You're not allocating anything, you're overwriting the same data on the stack (which then goes out of scope when the loop exits.
In C++, you allocate memory with the new operator. In C you'd use malloc. So a minimal rewrite of your code would be something like this (in C, since that seems to be what you're writing)
// Allocate enough space for the array of `WF_LIST_WORKUNIT_P_FE`s
WF_LIST_WORKUNIT_P_FE listWU = malloc(sizeof(WF_STRUCT_WORKUNIT_FE) * nbrRequested);
memset(listWU, 0, sizeof(WF_STRUCT_WORKUNIT_FE) * nbrRequested));
Of course, this just sets every struct in the array to 0, rather than a more meaningful initialization, if that is what you want.