使用带有数组参数的函数指针的分段错误

Spe*_*eed 0 c arrays function-pointers implicit-conversion function-declaration

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

\n

主要.c:

\n
\n#include <stdio.h>\n\nint sumOfElements(int *arr, int arr_elements);\n\nint main()\n{\n\n    int (*ptr)(int,int) = NULL;\n    ptr = sumOfElements;\n    int a[] = {128, 64, 32, 16, 8, 4, 2, 1};\n    printf("Total of price is: %d", ptr(a, 8));\n\n}\n\nint sumOfElements(int *arr, int arr_elements)\n{\n    int k =0;\n    int total;\n    for(;k < arr_elements;k++)\n    {\n        total += arr[k];\n    }\n    return total;\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
main.c:17:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]                               \nmain.c:19:41: warning: passing argument 1 of \xe2\x80\x98ptr\xe2\x80\x99 makes integer from pointer without a cast [-Wint-conversion]              \nmain.c:19:41: note: expected \xe2\x80\x98int\xe2\x80\x99 but argument is of type \xe2\x80\x98int *\xe2\x80\x99    \nSegmentation fault (core dumped) \n
Run Code Online (Sandbox Code Playgroud)\n

由于我仍在学习它,我不确定是否要接触代码,因为,就像我之前说过的,它可以在没有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

\n

Vla*_*cow 5

对于初学者来说,指针的声明如下

int (*ptr)(int,int) = NULL;
Run Code Online (Sandbox Code Playgroud)

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

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

int sumOfElements(int *arr, int arr_elements);
Run Code Online (Sandbox Code Playgroud)

也就是说第一个参数具有类型int *而不是int

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

long long int sumOfElements( const int *arr, size_t arr_elements);
Run Code Online (Sandbox Code Playgroud)

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

相应地,指针应声明为

long long int (*ptr)( const int *, size_t ) = NULL;
Run Code Online (Sandbox Code Playgroud)

该函数应该这样调用

printf("Total of price is: %lld", ptr(a, sizeof( a ) / sizeof( *a ) ) );
Run Code Online (Sandbox Code Playgroud)

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

int total;
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)