Bra_Hancock 2015-12-05 07:02 采纳率: 0%
浏览 1529
已采纳

函数作参数,也可以不写成指针形式?

下面的代码是书上的例子 main调用process再调arr
书上是用函数指针 然后我改了一下 发现不用指针 效果一样
但是网上一般都用指针形式 不用指针有什么弊端?

#include <iostream>
#include <cstdlib>
using namespace std;
#define N 5
/*
void process(int* x, int n,int (*fun)(int*,int))
{
    int result;
    result = (*fun)(x,n);
    cout<<result<<endl;
}
*/
void process(int* x, int n,int fun(int*,int))
{
    int result;
    result = fun(x,n);
    cout<<result<<endl;
}
int arr_max(int x[],int n)
{
    int max=x[0],k;
    for(k=1;k<n;k++)
    {
        if(max<x[k])
            max= x[k];      
    }
    return max;
}
int arr_min(int x[],int n)
{
    int min=x[0],k;
    for(k=1;k<n;k++)
    {
        if(min>x[k])
            min= x[k];
    }
    return min;
}
int main()
{
    int a[N] = {10,25,33,15,27},choice;
    cout<<"Input your choice:";
    cin>>choice;
    switch(choice)
    {
    case 1:cout<<"max = ";
        process(a,N,arr_max);
        break;
    case 2:cout<<"min = ";
        process(a,N,arr_min);
        break;
    }
    system("pause");
    return 0;
}
  • 写回答

3条回答 默认 最新

  • ysuwood 2015-12-05 08:03
    关注
     void process(int* x, int n,int (*fun)(int*,int))
     void process(int* x, int n,int fun(int*,int))
    

    作为函数形参,这两种方式是等价的,都是定义了fun函数指针变量,和数组一样:

     int fun(int *x, int n)
     int fun(int x[100],intn)
    

    在形参里定义数组长度没有意义,实质是定义了一个指针变量。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?