Example of using function pointers (refer to linux-kernel code)

Source: Internet
Author: User

This article has xhz1234 (Xu Hongzhi) to write, reprint please indicate source.

http://blog.csdn.net/xhz1234/article/details/36635083

Xu Hongzhi


Recently read the linux-kernel code, found that a lot of places use function pointers, so you write an example program, for reference:

#include <stdlib.h> #include <stdio.h> #define AddOne 0#define minusone 1#define S_OK 0#define s_err-1typedef Int (*DIR_FN) (int *data); function pointer//actual function 1int add_func (int *data) {(*data) ++;return S_OK;} The actual function 2int minus_func (int *data) {(*data)--;return S_OK;} Core: According to the parameter cmd, get the corresponding FUNCDIR_FN lookup_ctl (int cmd) {DIR_FN fn = null;switch (cmd) {case ADDONE:FN = Add_func;break;case MINUSONE:FN = Minus_func;break;default:break;} return fn;} int main (void) {int data = 100;int cmd = -1;DIR_FN fn = null;printf ("Input the cmd<0 Add, 1 minus>\n"); scanf ("%d", &A Mp;cmd); fn = Lookup_ctl (cmd), fn (&data);p rintf ("Result is:%d\n", data); return 0;}




This article has xhz123 (Xu Hongzhi) to write, reprint please indicate source.

Xu Hongzhi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.