繁体   English   中英

尝试添加数组元素时出现分段错误

[英]Segmentation fault when trying to add elements of an array

我正在尝试创建一个函数,该函数返回结果作为数组中元素的总和。 当我尝试运行程序时,出现分段错误。 有人能指出我正确的方向吗? 谢谢!

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

您需要分配内存。 仅声明一个指针是不够的。 您可以这样操作: array=malloc(numberOfElements*sizeof(*array));

同样,尽管可以从main函数返回result ,但是您不应该这样做。 main的返回值通常用于错误检查。 将程序结尾更改为

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

返回0通常表示没有错误发生。

您遇到的问题是,如果使用的是指针而不是固定大小的数组,则在C中需要手动分配内存。

通常,这是通过调用malloc来完成的,该函数将返回一个空指针(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;
}

您还尝试在main函数中返回结果,但是C中main的返回值用于表示程序是否终止而没有错误(由返回值0表示)或没有遇到任何问题(任何值)而不是0)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM