我试图创建一个函数,返回数组中元素的总和。当我尝试运行该程序时,出现分段错误。有人能指点我正确的方向吗?谢谢!尝试添加数组元素时出现分段错误
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'或类似的方法分配一块内存。 –