Summary of three ways to use function Pointers in C language

  • 2020-05-30 20:50:36
  • OfStack

Summary of three ways to use function Pointers in the C language

Here to share 1 of their own experience, hope to share with you 1 technology, if you have any shortcomings, please correct. Writing this article, I hope you can grow up together. I also believe that there is no high or low technology, only complementary, only sharing, to make each other more growth.

Definition: int (*p)(int x, int y);

Implementation code:


#include <stdio.h>
int sum(int x, int y){
  return x + y;
}
int reduce(int x, int y){
  return x - y;
}
int multiply(int x, int y){
  return x * y;
}
float divide(int x, int y){
  if(y ==0)
    return 0;
  else
    return x *1.0f/ y;
}

struct Student{
  int age;
  float weight;
  char *name;
  void(*studentP());
}

int main(int argc, const char * argv[])
{

  // 1. Define function pointer 
  int (*p)(int x, int y);
  // 2. Initialize the 
  p = sum;
  // 3. The assignment 
  int s = p(3,2);
  // 4. print 
  printf("%d\n",s);//=5;

  //--------------
  printf(" Please enter a number 1,2,3,4\n");
  int num;
  scanf("%d",&num);

  switch (num) {
    case 1:
      p = sum;
      break;
    case 2:
      p = reduce;
      break;
    case 3:
      p = multiply;
      break;
    case 4:
      p = divide;
      break;

  }
  int result = p(22,2);

  printf("%d\n",result);

  // Structure: 
  struct Student stu = (22,88,"tom",studp);
  printf(" Structural length =%d",sizeof(stu));
  //1.
  stu.studp;
  //2.
  struct stu* stp = &stu;
  (*stp).studp;
  //3.
  stp -> studp;

  return 0;
}

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: