2017-12-03 292 views
1

我試圖創建一個函數,返回數組中元素的總和。當我嘗試運行該程序時,出現分段錯誤。有人能指點我正確的方向嗎?謝謝!嘗試添加數組元素時出現分段錯誤

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

你應該看看'malloc'。 –

+0

您無法將值分配給尚未分配的內存。在將值分配給數組之前,使用'malloc'或類似的方法分配一塊內存。 –

回答

0

您遇到的問題是,如果您使用的是指針而不是固定大小的數組,則需要在C中手動分配內存。

這通常是通過調用malloc完成的,它會返回一個void-pointer(void *),在分配它之前需要將其轉換爲所需的類型(在您的情況下爲int *)。

還需要注意的是,使用malloc時,需要指定要分配的字節數。這意味着你不能僅僅用你想要存儲在裏面的整數來調用它,而是必須把這個數乘以一個整數佔據的字節數(這取決於你使用的硬件和操作系統,因此你應該使用sizeof(int)來達到這個目的,在編譯時計算這個大小)。

我修改你的代碼的它如何做一個工作示例:

#include <stdio.h> 
#include <stdlib.h> 


int arraySum (int array[], int numberOfElements) { 
    int result = 0; 

    int i; 
    for (i = 0; i < numberOfElements; i++) { 
     result += array[i]; 
    } 

    return result; 
} 

int main(int argc, char **argv) { 
    int numberOfElements; 
    int *array = NULL; 

    printf("How many elements would you like in your array: "); 
    scanf("%i", &numberOfElements); 

    array = (int*) malloc(numberOfElements * sizeof(int)); 

    printf("\nPlease list the values of the elements in the array: "); 

    int i; 
    for (i = 0; i < numberOfElements; i++) { 
     scanf("%i", &array[i]); 
    } 

    int result = arraySum(array, numberOfElements); 

    printf("\n\nThe result is: %d\n", result); 

    return 0; 
} 

您還試圖在主函數返回的結果,而是主要在C中的返回值是用來表示程序是否無錯地終止(返回值爲0)或沒有遇到任何問題(0以外的任何值)。

+0

另外,爲了澄清:你遇到的分段錯誤是你嘗試訪問內存中非法地址的信號,發生這種情況,因爲你沒有爲你的數組分配任何內存,並且它指向NULL(這是一個地址解除引用是非法的) – C8263A20

0

您需要分配內存。僅僅聲明一個指針是不夠的。你這樣做:array=malloc(numberOfElements*sizeof(*array));

此外,雖然有可能從main功能返回result,你不應該這樣做。 main的返回值通常用於錯誤檢查。將程序的結尾更改爲

printf("Sum: %d\n", result); 
return 0; 

返回0通常表示沒有錯誤發生。

相關問題