arrays - 使用带有数组参数的函数指针的分段错误
问题描述
今天我开始学习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
解决方案
对于初学者来说,指针声明为
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;
}
推荐阅读
- c - 使用字符串在 C 中创建优先级队列
- html - 如何在本地 HTML 文件中捕获页面未找到错误
- javascript - 像轮子一样围绕中心点旋转三角形
- javascript - 单击某个 css 类或 ID 时使用户的视口向上滚动
- r - `levels<-`(`*tmp*`, value = as.character(levels)) 中的错误:因子级别 [3] 重复
- android-emulator - 无法在具有 Core 2 cpu 的 PC 上运行模拟器
- r - Shiny中具有不同数据集的反应性条形图
- android - android中的slider和seekbar有什么区别
- c# - C#:什么是 "=> . <=" 运算符?
- reactjs - 我可以将浏览器或模拟器视图嵌入到 vs 代码中吗