0
我學習C語言編程並通過陣列多種功能,不知道什麼時候,爲什麼我的陣列是由東西覆蓋,幫我調試,並當場我的錯誤代碼:C函數和數組
#include <stdio.h>
int insertNumbers(int *numbers, int howManny){
int i;
for(i=0; i< howManny; i++){
printf("Insert number:");
scanf("%d", &numbers[i]);
}
printf("\nNumbers :(insertNumbers function)\n");
for (int i = 0; i < howManny; ++i) {
printf("%d: %d\n",i, numbers[i]);
}
return *numbers;
}
int add(int *numbers, int howManny){
int sum = 0;
for (int i = 0; i < howManny; ++i) {
sum = sum + numbers[i];
}
return sum;
}
void printArray(int *numbers, int howManny){
printf("\nNumbers:(print array function)\n");
for (int i = 0; i < howManny; ++i) {
printf("%d: %d\n",i, numbers[i]);
}
}
int main(){
int numbers, howManny, sum = 0, numbersArray;
printf("How manny numbers do you want?");
scanf("%d", &howManny);
numbersArray = insertNumbers(&numbers, howManny);
sum = add(&numbers, howManny);
printf("Total sum is: %d",sum);
printArray(&numbersArray, howManny);
return 0;
}
結果是
How manny numbers do you want?3
3
Insert number:10
10
Insert number:20
20
Insert number:30
30
Numbers :(insertNumbers function)
0: 10
1: 20
2: 30
Total sum is: 60
Numbers:(print array function)
0: 10
1: 3
2: 10
看起來像我的數組的地方,但不知道什麼時候,爲什麼覆蓋
甚至當我嘗試使用
printArray(&numbers, howManny);
仍然沒有工作,但得到10,10,50值
'numbers'是一個'int',而不是一個數組。 – aschepler
'numbers'不是數組 – Arash
看起來像使用int數[howManny]',但仍然讓我困惑,它如何在insertNumbers函數中工作,是因爲它的本地函數範圍? – Night5talker