C语言,函数指针与指针函数

本文通过两个实例介绍C++中如何使用函数指针及字符串比较。首先演示了通过函数返回两个字符串中较长的一个,其次展示了如何定义并使用函数指针来调用一个函数,以找出两个数中的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <iostream>
using  namespace std;
char* func(char* s1,char* s2){
if(strcmp(s1,s2)>=0){
return s1;
}else{
return s2;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str1="abcdef"; //	char str1[]="abcdef" 正确
char *str2="frhu";		//char str2[]="ccccef";正确
char *longest=func(str1,str2);
cout<<longest<<endl;
system("pause");
return 0;
}
//frhu
//请按任意键继续. . .

/////////函数指针,是指向函数的指针,把函数的地址赋给该指针;
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using  namespace std;

int  max(int a,int b){

if(a>b){
return a;
}else{
return b;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int (*pmax)(int ,int);
int x=2,y=3,maxval;
pmax=max;////	int (*pmax)(int ,int);和int  max(int a,int b)指向相同的地址,
//所以pmax(x,y);运行的还是int  max(int a,int b)
//maxval=pmax(x,y);///正确
maxval=(*pmax)(x,y);///正确
cout<<"最大值:"<<maxval<<endl;
system("pause");
return 0;
}
//最大值:3
//请按任意键继续. . .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二十六画生的博客

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值