首页 > 其他 > 详细

function pointer

时间:2020-04-14 09:41:40      阅读:71      评论:0      收藏:0      [点我收藏+]
#include <stdio.h> 
// A normal function with an int parameter 
// and void return type 
void fun(int a) 
{ 
	printf("Value of a is %d\n", a); 
} 

int main() 
{ 
	// fun_ptr is a pointer to function fun() 
	void (*fun_ptr)(int) = &fun; 

	/* The above line is equivalent of following two 
	void (*fun_ptr)(int); 
	fun_ptr = &fun; 
	*/

	// Invoking fun() using fun_ptr 
	(*fun_ptr)(10); 

	return 0; 
} 

 

 

 

  

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code.

2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.

3) A function’s name can also be used to get functions’ address. For example, in the below program, we have removed address operator ‘&’ in assignment. We have also changed function call by removing *, the program still works.

filter_none

edit

play_arrow

brightness_4

#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
    printf("Value of a is %d\n", a);
}
  
int main()
    void (*fun_ptr)(int) = fun;  // & removed
  
    fun_ptr(10);  // * removed
  
    return 0;

 5) Function pointer can be used in place of switch case. For example, in below program, user is asked for a choice between 0 and 2 to do different tasks.

#include <stdio.h> 
void add(int a, int b) 
{ 
	printf("Addition is %d\n", a+b); 
} 
void subtract(int a, int b) 
{ 
	printf("Subtraction is %d\n", a-b); 
} 
void multiply(int a, int b) 
{ 
	printf("Multiplication is %d\n", a*b); 
} 

int main() 
{ 
	// fun_ptr_arr is an array of function pointers 
	void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply}; 
	unsigned int ch, a = 15, b = 10; 

	printf("Enter Choice: 0 for add, 1 for subtract and 2 "
			"for multiply\n"); 
	scanf("%d", &ch); 

	if (ch > 2) return 0; 

	(*fun_ptr_arr[ch])(a, b); 

	return 0; 
} 

  

typedef can be used to simplify the usage of function pointers. 

 

#include<stdio.h>

void print_to_n(int n)
{
    for (int i = 1; i <= n; ++i)
        printf("%d\n", i);
}

void print_n(int n)
{
    printf("%d\n, n);
}



typedef void (*printer_t)(int);
printer_t p = &print_to_n;
p(5);   

The above code is equivlant to:

void (*p)(int) = &print_to_n;
(*p)(5);
 

 

function pointer

原文:https://www.cnblogs.com/anyu686/p/12694771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!