为什么它显示运行时错误?它没有给出任何输出?

时间:2016-08-29 17:09:12

标签: c

/ 此代码用于旋转数组,其中n个条目没有k次            并且在indexz q输出数组元素没有时间 /我的问题在于它显示运行时错误为什么会发生这种情况。这个问题实际上来自黑客等级,它是由圆形数组旋转的名称在算法中的implimentation部分。这段代码中有任何错误。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int n,k,q;
    int a[n];
    scanf("%d%d%d",&n,&k,&q);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    for(int j=0;j<k;j++)/*this is for rotating the array*/
    {
        int y=a[n-1];
        for(int x=n-2;x>=0;x--)
            a[x+1]=a[x];
        a[0]=y;
    }  
    for(int b=0;b<q;b++)
    {
        int z;
        scanf("%d",&z);
        printf("%d\n",a[z]);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:3)

问题:

int n,k,q;
int a[n];

在设置n的值之前,您正在创建一个大小为n的数组。

使用:

int n,k,q;

// Read a value into n first
if ( scanf("%d%d%d",&n,&k,&q) != 3 )
{
   // Deal with error
   return 1;
}

// Then define the array.
int a[n]; 
相关问题