我試圖創建一個函數,返回數組中元素的總和。當我嘗試運行該程序時,出現分段錯誤。有人能指點我正確的方向嗎?謝謝!嘗試添加數組元素時出現分段錯誤
int arraySum (int array[], int numberOfElements) {
int result = 0;
for (int i = 0; i < numberOfElements; i++)
{
result += array[i];
}
return result;
}
int main (void) {
int numberOfElements;
int *array = NULL;
printf("How many elements would you like in your array: ");
scanf("%i", &numberOfElements);
printf("\nPlease list the values of the elements in the array: ");
for (int i = 0; i < numberOfElements; i++)
{
scanf("%i", &array[i]);
}
int result = arraySum(array, numberOfElements);
return result;
}
你應該看看'malloc'。 –
您無法將值分配給尚未分配的內存。在將值分配給數組之前,使用'malloc'或類似的方法分配一塊內存。 –