我需要为每次迭代定义数组长度以对数组元素执行一些操作。 但是每次迭代的数组大小都不同。因此,我将数组大小定义为 arr[totalLen]: 但 totalLen 每次迭代都会变化。
- 我不能使用 malloc,因为我正在工作的实时系统不允许动态内存分配
1) 这是定义数组的正确方法吗?元素“arr”的范围(内存分配和变量的生命周期)是否每次迭代都会改变?
或者
2) 在 for 循环之前定义具有最大元素数的数组是首选方法吗?
/* 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++;
最佳答案
这有点奇怪。在 C99 之前不支持可变长度数组,C99 支持,但随后在 C11 中降级为可选,这意味着 C11 编译器可能不支持它们但仍遵循标准。
我自己会使用 malloc
。
关于我可以在循环中定义一个数组,其大小在每次迭代中都不同吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45910874/