Reputation: 251
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.
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++;
Upvotes: 1
Views: 566
Reputation: 16046
It's generally a bad idea to use a VLA if the size could ever be "too big". You could overflow the stack, or even if you don't, you could kill cache efficiency (and cache is king).
One possible value for "too big" is 4096 bytes, but YMMV.
So, only use VLAs to save stack space (and thus be cache friendlier) if you know it won't always take the full 4096 (or whatever) bytes. Otherwise, use malloc
.
If this answer seems too complicated (it's often more than you need), simply don't use VLAs at all.
Upvotes: 0
Reputation: 36
Defining a array length like that is not good a practice. because every system have limited memory allocated, if you didnt define size of array before loop iteration your program might crash in certain point. So, its always good pratice to allocate memory for array before loop .. Or you might use malloc... Tht might be the bad side of using array because you might maybe allocate more memory which might not need. also if you didnt define size of memory before iteration memory allocation will change every iteration. I hope you got the point
Upvotes: 0
Reputation: 17040
This is kind of a weird one. Variable length arrays are not supported prior to C99, are supported by C99, but then are downgraded to optional in C11, meaning that it's possible for a C11 compiler not to support them and still follow the standard.
I'd just use malloc
, myself.
Upvotes: 0