2013-09-23 38 views
1

基本上,我試圖編寫一個簡單的C函數,提示用戶輸入數組長度,然後要求用戶輸入數組的值(整數)。從用戶定義數組長度存儲數組值

樣本輸出期望:

Enter Array Length: 5 
Enter values for the array: 
1 2 3 6 7 

The current array is: 
1 2 3 6 7 

這是我此刻的代碼。我覺得這應該是有效的,但是有了C的基本知識,就會導致分段錯誤。

int intersect() 
{ 
    int size, index, input; 
    printf("Enter the size of the arrays:\n"); 
    scanf("%d", &size); 

    int arr1[size], arr2[size]; 
    index = 0; 
    printf("Enter the elements of the first array:\n"); 
    while (index < sizeof(arr1)) 
    { 
     scanf("%d ", &input); 
     arr1[index] = input; 
     index = index + 1; 
    } 

    printf("The current array is:\n %d", arr1); 
} 

我不明白如何收集長度爲用戶定義的數組的輸入。任何解釋讚賞!

+0

你有一個index-out-bound的問題,正確'while(index

+0

閱讀:[在C中打印數組時出現的奇怪行爲](http://stackoverflow.com/questions/18009725/weird-behavior-when-printing-array-in-c/18009736#18009736) –

回答

6

sizeof返回以字節爲單位佔用的內存,而不是數組長度。所以基本上你要檢查索引是否小於40size of Integer * array length)。由於數組沒有空間來存儲40個整數值,因此它給出了未定義的行爲(某些時間分段錯誤)。

而應該改變

while (index < sizeof(arr1)) 

while (index < size) 

其次也是正確的:

printf("The current array is:\n %d", arr1); 
//        ^^address    

for (i = 0; i < size, i++) 
    printf("The current array is:\n %d", arr1[i]); 

要麼打印地址使用%p

+0

謝謝!我將它改爲while(索引<=(size - 1)) – Micah

+0

@Micah您還應該更新printf語句以打印格里傑什提到的數組值,否則它只會打印數組第一個元素的地址 – hrv

+2

@hrv我不想一次又一次地寫出類似的(我鏈接的)答案,所以更新你的答案希望你喜歡它:) –