2012-06-02 45 views
0

我想創建一個數組,其大小要在運行時確定,即用戶輸入。用c語言在運行時確定大小的數組?

我試圖做這樣的:

printf("enter the size of array \n"); 

scanf("%d",&n); 

int a[n]; 

但是,這導致錯誤。

如何設置這樣的數組大小?

+0

你在使用什麼編譯器,它顯示什麼錯誤? –

回答

2

除非您使用C99(或更新版),否則您需要手動分配內存,例如,使用calloc()

int *a = calloc(n, sizeof(int)); // allocate memory for n ints 
// here you can use a[i] for any 0 <= i < n 
free(a); // release the memory 

如果您確實有符合C99的編譯器,例如GCC與--std=c99,你的代碼工作正常:

> cat dynarray.c 
#include <stdio.h> 
int main() { 
     printf("enter the size of array \n"); 
     int n, i; 
     scanf("%d",&n); 
     int a[n]; 
     for(i = 0; i < n; i++) a[i] = 1337; 
     for(i = 0; i < n; i++) printf("%d ", a[i]); 
} 
> gcc --std=c99 -o dynarray dynarray.c 
> ./dynarray 
enter the size of array 
2 
1337 1337 
+1

爲什麼如果OP有一個符合c99的編譯器? –

+0

「除非你使用C99」。 C11沒有刪除可變長度數組。 –

+2

heh,nitpicker:p – ThiefMaster

0

您需要包括stdio.h,申報n,把你的代碼的功能。除此之外,你所做的一切應該工作。

#include <stdio.h> 

int main(void) 
{ 
     int n; 
     printf("enter the size of array \n"); 
     scanf("%d",&n); 
     int a[n]; 
} 
+0

並將您的編譯器切換到C99模式 – ThiefMaster

+0

如果downvoting請留下原因。謝謝。 –