【问题标题】:Hackerrank circular array rotation segmentation faultsHackerrank 圆阵列旋转分段错误
【发布时间】:2017-01-07 04:34:32
【问题描述】:

我的以下代码在示例输入中成功运行,但在 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 定义为数组,问题仍然存在。

【问题讨论】:

  • 购买其中一个出现故障的输入(应该是 5 个 hackos)并使用gdb
  • 嗯...有趣:int q; int index[q];
  • no @kartikeykant18 你不能......而且这里 q 未初始化。
  • int *a(malloc(sizeof(int) * n)); 编译吗?
  • 你怎么能打出这样的错字?您将复制/粘贴 if 这确实是您的程序。但我的观点是:当n &lt; 2int ap = a[n-2]; 会带来麻烦。

标签: c arrays pointers


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2016-01-17
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多