gpt4 book ai didi

c - C 循环中的动态数组

转载 作者:行者123 更新时间:2023-11-30 21:20:56 24 4
gpt4 key购买 nike

我想创建一个代码,它将根据用户需求存储新数组并对其执行特定的一组操作。因此,考虑到在对数组执行操作后我实际上并不需要存储该数组,我想到了覆盖同一个数组,但这就是我遇到问题的地方。

int main() 
{
int i, T;

scanf("%d", &T);
int res[T];//for T cases I'll have T outputs so saving it in an array

for(i=0; i<T; i++)
{
int size, j;
scanf("%d", &size);
int ary[size];
for(j=0; j<size; j++)
{
scanf("%d ", &ary[j]);
}
//In each case I'm just declaring an array and getting a result n storing in another array
res[i]=fn(ary, size);//fn returns 1 if array forms Circular Prime else 0
}

for(i=0; i<T; i++)
{
if(res[i]==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}

最佳答案

C89 不允许使用非常量绑定(bind)说明符创建数组。 C99引入了这个概念,C11将其作为可选功能。为了 100% 可移植,您应该使用动态内存分配来解决这个问题:

int main() {
int i, T;
scanf("%d", &T);
//DYNAMIC MEMORY ALLOCATION
int *res = malloc(T * sizeof(int)); //for T cases I'll have T outputs so saving it in an array
if (res == NULL) { //Check for failure
/* failure, out of memory */
return 1;
}
for(i=0; i<T; i++){
int size, j;
scanf("%d", &size);
//DYNAMIC MEMORY ALLOCATION
int *ary = malloc(size * sizeof(int));
if (ary == NULL) { //Check for failure
/* failure, out of memory */
return 1;
}
for(j=0; j<size; j++){
scanf("%d", &ary[j]);
} //In each case I'm just declaring an array and getting a result n storing in another array
res[i]=fn(ary, size);//Called a function got a result stored in res[]
//FREE ALLOCATED MEMORY
free(ary);
}
for(i=0; i<T; i++){
if(res[i]==1)
printf("YES\n");
else
printf("NO\n");
}
//FREE ALLOCATED MEMORY
free(res);
return 0;
}

关于c - C 循环中的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32630869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com