2017-12-03 293 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通常表示没有错误发生。

相关问题