首页 > 试题广场 >

以下关于C语言中函数指针数组的用法,正确的是?```cint

[单选题]
以下关于C语言中函数指针数组的用法,正确的是?
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
  • int *ops[](int, int) = {add, sub, mul};
  • int (*ops[])(int, int) = {add, sub, mul};
  • int (ops[])(int, int) = {add, sub, mul};
  • int (*ops)(int, int)[] = {add, sub, mul};
一、3个核心概念(优先级口诀: []、() 优先级 >  * ,括号可以改变运算优先级) 1、指针函数:本质是【函数】,函数返回值是指针 格式: 返回类型 *函数名(参数列表)  示例: int *fun(int a,int b);  - 解读: fun  是普通函数,函数执行结束返回一个 int* 整型指针; - 关键: * 和函数名没有括号包裹, () 优先级更高,先和 fun 结合成函数。 2、函数指针:本质是【指针变量】,用来存函数的首地址 格式: 返回类型 (*指针名)(参数列表)  示例: int (*p)(int a,int b);  - 解读:必须用括号把 *p 包起来, p 是指针,指向「入参2个int、返回int」的函数; - 用法: p = add; (函数名=函数首地址),调用 p(3,5) 等价 add(3,5) 。 3、函数指针数组(本题考点B选项):本质是【数组】,数组里每一个元素都是函数指针 格式: 返回类型 (*数组名[])(参数列表)   int (*ops[])(int,int) = {add,sub,mul};  -  ops 是数组, ops[0] 存 add 地址、 ops[1] 存 sub 地址; - 调用: ops[0](10,2)  → 等价 add(10,2) 。 二、逐个拆解题目4个选项 已知函数: add/sub/mul 都是 int (int,int) 型函数 A: int *ops[](int,int)={add,sub,mul};  ❌错误  [] 优先级高于 * , ops[] 先结合数组符号,整句含义:ops是数组,数组每个元素是【指针函数】(返回int*的函数),C语言不支持函数存入数组,语法错误。 B: int (*ops[])(int,int)={add,sub,mul};  ✅正确  (*ops[]) 括号限定: ops 是数组,数组内每个元素是 int(*)(int,int) 类型函数指针,刚好匹配add/sub/mul三个函数,是标准函数指针数组写法。 C: int (ops[])(int,int)={add,sub,mul};  ❌错误 没有 * ,代表 ops 是普通函数数组,C语言语法禁止把函数作为数组元素。 D: int (*ops)(int,int)[]={add,sub,mul};  ❌错误 含义变成: ops 是一个指针,指向「存放 int(int,int) 类型的数组」,语法畸形、和题目需求无关。 三、速记区分口诀 1.  int *p();  → 指针函数:p是函数,返回指针 2.  int (*p)();  → 函数指针:p是指针,指向函数 3.  int (*p[])();  → 函数指针数组:p是数组,存一堆函数指针 四、实操示例代码 c #include<stdio.h> int add(int a,int b){return a+b;} int sub(int a,int b){return a-b;} int mul(int a,int b){return a*b;} int main(void) { //定义函数指针数组 int (*ops[])(int,int)={add,sub,mul}; printf("%d",ops[0](5,3));//5+3=8 printf("%d",ops[1](5,3));//5-3=2 printf("%d",ops[2](5,3));//5*3=15 return 0; }   需要我出两道同类小题帮你巩固吗?</stdio.h>
发表于 今天 13:11:05 回复(0)