高级指针话题

谈一下函数指针的使用,下面是例子。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#define MAXN 5


//函数指针,当函数调用时会隐式的由编译器转换为函数指针再函数调用操作符调用函数;
void f(int x) {
	printf("FFF\n");
}
void (*pf)(int) = f;

int main() {
	f(1);
	(*pf)(1);
	pf(1);
	return 0;
}

//插一段代码,链表查找元素的,利用函数指针来写一个回调函数,这样可以查找任何类型的值;
int compare_ints(void const *a, void const *b) {
	if (*(int *)a == *(int *)b) { //比较函数参数必须声明为void*来匹配查找函数原型,比较的是int,强制转换为int*;
		return 0;}
	return 1;
}
Node *search_list(Node *node, void const *value, int (*compare)(void const *, void const *)) {
	while (node != NULL) {
		if (compare(&node->value, value) == 0) {
			break;
		}
		node = node->link;
	}
	return node;
}

//若为字符串比较则可直接调用strcmp,即为search_list(root,"desired_value",strcmp);

转换表,举一个例子,写简易的计算器时容易想到switch,但很冗杂,若用到函数指针数组来写便很方便,唯一要留心之就是要确保这些函数的原型出现在这个数组声明之前。


double add(double,double);
double sub(double,double);
double mul(double,double);
double div(double,double);
...
double (*oper_func[])(double ,double ){add,sub,mul,div,...
}

命令行参数

处理命令行参数时指向指针的指针的一个用武之地。

int main(int argc, char **argv) {
	printf("%d\n", argc);
	while (*argv != NULL) {
		printf("%s\n", *argv++);
	}
	return 0;
}

字符串常量

int main() {
	char *p = "abc";
	printf("%c\n", *("abc" + 1));
	printf("%c\n", "abc"[2]);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值