首页 > 解决方案 > 使用带有数组参数的函数指针的分段错误

问题描述

今天我开始学习C,我被函数指针困住了。这是我的代码:

主.c:


#include <stdio.h>

int sumOfElements(int *arr, int arr_elements);

int main()
{

    int (*ptr)(int,int) = NULL;
    ptr = sumOfElements;
    int a[] = {128, 64, 32, 16, 8, 4, 2, 1};
    printf("Total of price is: %d", ptr(a, 8));

}

int sumOfElements(int *arr, int arr_elements)
{
    int k =0;
    int total;
    for(;k < arr_elements;k++)
    {
        total += arr[k];
    }
    return total;
}

我要做的是访问sumOfElements函数中数组的元素。当我正常调用它时,一切都很顺利。当我尝试使用 时function pointer,编译器之前会向我抛出一些警告,然后是Segmentation Fault错误:

main.c:17:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]                               
main.c:19:41: warning: passing argument 1 of ‘ptr’ makes integer from pointer without a cast [-Wint-conversion]              
main.c:19:41: note: expected ‘int’ but argument is of type ‘int *’    
Segmentation fault (core dumped) 

由于我仍在学习它,我不确定是否要接触代码,因为就像我之前所说的,它可以在没有function pointer. 现在,错误main.c:17:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types],我并没有真正理解它,因为它们都是int。所以,如果你也能解释一下,那会为我节省很多时间。那么,为什么它只Segmentation Fault (core dumped)在我使用时抛出funptr?我所知道的是,分段错误是当我们尝试访问仅read-only或它的内存时out-of-bound

标签: arrayscfunction-pointersimplicit-conversionfunction-declaration

解决方案


对于初学者来说,指针声明为

int (*ptr)(int,int) = NULL;

也就是说,它是一个指向具有两个类型参数的函数的指针int

但是函数sumOfElements有不同类型的参数

int sumOfElements(int *arr, int arr_elements);

那就是第一个参数的类型int *不是int.

此外,由于数组在函数内没有改变,所以最好像这样声明函数

long long int sumOfElements( const int *arr, size_t arr_elements);

函数返回类型long long int不是,int因为它降低了数组元素总和溢出的风险。

相应地,指针应声明为

long long int (*ptr)( const int *, size_t ) = NULL;

并且该函数应该被称为

printf("Total of price is: %lld", ptr(a, sizeof( a ) / sizeof( *a ) ) );

在您忘记初始化变量的函数中total

int total;

该函数可以通过以下方式定义

long long int sumOfElements( const int *arr, size_t arr_elements )
{
    long long int total = 0;

    while( arr_elements-- )
    {
        total += arr[arr_elements];
    }

    return total;
}

推荐阅读