我的以下代码在示例输入中成功运行,但在 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/