Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 尝试编写函数对数组元素求和时出现分段错误_C_Arrays - Fatal编程技术网

C 尝试编写函数对数组元素求和时出现分段错误

C 尝试编写函数对数组元素求和时出现分段错误,c,arrays,C,Arrays,我已经在这个问题上纠缠了一段时间了,我不知道该如何处理这个问题 #include <stdio.h> #include <stdlib.h> int ItSum(int *array, int array_size); int main(){ int array_size, isum, sum; printf("\nPlease enter the size of the array:"); scanf("%d",&array_size)

我已经在这个问题上纠缠了一段时间了,我不知道该如何处理这个问题

#include <stdio.h>
#include <stdlib.h>
int ItSum(int *array, int array_size);

int main(){
    int array_size, isum, sum;
    printf("\nPlease enter the size of the array:");
    scanf("%d",&array_size);
    int *array;
    array=(int*)malloc(array_size*sizeof(int));
    printf("Please enter the elements of the array:");
    int i;
    for(i=0; i<array_size;i++)
        scanf("%d",&array[i]);
    printf("\nThe elements of the array are:");
    for(i=0; i<array_size; i++)
        printf(" %d", array[i]);

    isum=ItSum(*array,array_size);
    printf("\nThe sum of the elements using iteration is:%d", isum);

    free (array);
    return 0;
}

int ItSum(int *array, int array_size){
    int x, itsum;
    itsum=0;    
    for (x=0;x<array_size;x++)
        itsum+=array[x];
    return itsum;
}
#包括
#包括
int ItSum(int*数组,int数组大小);
int main(){
int数组大小,isum,sum;
printf(“\n请输入数组的大小:”);
scanf(“%d”和数组大小);
int*数组;
数组=(int*)malloc(数组大小*sizeof(int));
printf(“请输入数组的元素:”);
int i;

对于(i=0;i,问题在编译器警告中公开:

$ cc -Wall test.c
test.c:19:16: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'int *'; remove *
      [-Wint-conversion]
    isum=ItSum(*array,array_size);
               ^~~~~~
test.c:3:16: note: passing argument to parameter 'array' here
int ItSum(int *array, int array_size);
               ^
test.c:6:27: warning: unused variable 'sum' [-Wunused-variable]
    int array_size, isum, sum;
                      ^
生成2个警告

这一行:

isum=ItSum(*array,array_size);
应该是:

isum=ItSum(array,array_size);

这里您将
*array
作为参数传递,但您应该只传递
array
,它是指向
int
的指针,因为函数将指向
int
的指针作为参数。
*array
引用地址处的值,因此将
int
作为参数传递,即数组的第一个值。

Ar您是否在编译此代码时打开了警告?编译器提示出了什么问题。使用
-Wall
gcc标记编译您的代码我还添加了-wextraahh,我最初写下了这一点,但编译器编译和运行程序花费了很长时间,所以我认为它是错误的。非常感谢您的帮助!将立即尝试此操作.
 isum=ItSum(*array,array_size);