c - Hackerrank 圆形阵列旋转分割错误

标签 c arrays pointers

我的以下代码在示例输入中成功运行,但在 13 个测试用例中出现段错误。

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    int k; 
    int q; 
    int index[q];
    scanf("%d %d %d",&n,&k,&q);
    int *a = (malloc(sizeof(int) * n));
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    for(int a0 = 0; a0 < q; a0++){
        int m; 
        scanf("%d",&m);
        index[a0] = m;
    }
    for(int i=0; i<k; i++){
        int ap = a[n-2];       

        for(int p=1; p<n-1; p++){
            a[p] = a[p-1];
        }
        a[0] = a[n-1];
        a[n-1] = ap;      


    }
    for(int j=0; j<q;j++){
        printf("%d\n", a[index[j]]);
    }

    return 0;
}

我无法找到段错误的位置。另请查看:where I asked about declaring a as a pointer using malloc

使用 malloc() 声明 a 可能会导致段错误,因为它不检查分配错误,但即使我将 a 定义为数组,问题仍然存在。

最佳答案

q 未初始化,但用作数组声明的参数。

在读取 q 的值后,您应该使用 malloc 分配索引数组。

关于c - Hackerrank 圆形阵列旋转分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513513/

相关文章:

c - 如何在 C 中管理动态字符串数组

c - 包含 Windows h (C) 时需要一个标识符

有条件地使用位运算符

c - 使用 fscanf 从文件中读取

c - 如何在函数之间传递数组

arrays - ruby 如何从哈希数组中删除元素?

c - 基数排序通过仅更改计数子例程的一个循环给出错误的答案

c++ - 宏中变量的范围

C++ - 错误 : expected primary-expression before '<<' token

C - if 条件中的指针