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



/此代码用于旋转数组n个条目k次输出数组元素在索引q没有时间/我的问题是,它显示了运行时错误,为什么它会这样发生。这个问题实际上来自黑客排名,在算法的实现部分中被称为循环数组旋转。这段代码有什么问题吗?

#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("%dn",a[z]);
    }
    return 0;
}

问题:

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]; 

最新更新