c - C 循环中的动态数组

标签 c arrays memory dynamic-memory-allocation

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

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/

相关文章:

c - GNU Make - 对非程序代码的依赖

c - 为什么数据不保存到结构中?

c++ - 声明后初始化 boost::array

function - 为什么某些流行语言中的函数只返回一种类型的结果?

c++ - 指针的大小是多少?它具体取决于什么?

c - 如何处理共享虚拟内存(Linux)

c++ - 相同功能的不同实现(c/c++)

c++ - 项目 : C vs C++ 中包含多个相同的头文件

c++ - Lambda 中数组衰减为指针

javascript - 从 JS 数组中删除重复值