Thursday, 7 September 2017

c - Can I define an array inside a loop with its size varying every iteration

I need to define array length for each iteration to do some operation on the array elements.
But the array size varies for every iteration. Hence I defined array size as arr[totalLen]: but the totalLen varies every iteration.





  • I can not use malloc since dynamic memory allocation is disallowed for the real time system I am working



1)
Is this a proper way of defining an array? Does the scope of the element "arr" (memory allocation and life of the variable) change every iteration?



Or




2) is it a preferred way to define an array before the for loop with maximum number of elements?



/* some code here - to get the task info */
while (task[i].info!= NULL)
{
printf("\n Task Name is %s", task[i].Name);
scenario1= scenario2= scenario3= scenario4= 0;
nvStruct = (int '*)(TablesPtr->NVData );

/* do something when each of the following scenario occurs */

if ((scenario1= (!strcmp(task[i].Name, "Scenario1"))) ||
(scenario2= (!strcmp(task[i].Name, "Scenario2"))) ||
(scenario3= (!strcmp(task[i].Name, "Scenario3"))) ||
(scenario4= (!strcmp(task[i].Name, "Scenario4"))))
{
totalLen = *(nvStruct+1); // size of the struct
printf("\nLength of the struct is %d", totalLen);

int32 arr[totalLen]; // is this proper usage?


for (uint32 len = 0; len < (totalLen)/4; len++)
arr[len] = *(nvStruct+len);

/* do something else with the array here */
....
i++;

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...