2016-08-29 88 views
-2

/這段代碼是用於旋轉陣列的n個no項目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; 
} 
+2

「有什麼不對在此代碼」 - 是的。 –

+0

'int a [n];' - 你能告訴這個數組的大小是多少? –

+0

請格式化您的代碼的可讀性。 – zhon

回答

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

使用變量作爲數組的大小是否合法? – hymie

+0

@hymie,是的。可變長度數組是自C99以來的標準的一部分。 –

+0

謝謝。在那之前我學了很多年了,並沒有跟上不斷變化的標準。 – hymie

相關問題