How to call a function using pointers in C language.

In the C language, functions can be called using pointers. The syntax for calling a function with a pointer is as follows:

  1. Declare a function pointer: define the type of function pointer using the function prototype.
返回类型 (*指针变量名)(参数列表);
  1. Assign the address of a function to a pointer variable: Assign the name (or address) of a function to a function pointer variable.
指针变量名 = 函数名;
  1. Call a function using a pointer variable: Use a pointer variable and the function call operator to invoke a function.
(*指针变量名)(参数列表);

Here is a sample code demonstrating how to call a function using pointers.

#include <stdio.h>

// 声明函数原型
void hello();

int main() {
    // 声明函数指针变量
    void (*funcPtr)();

    // 将函数地址赋值给指针变量
    funcPtr = hello;

    // 通过指针变量调用函数
    (*funcPtr)();

    return 0;
}

// 定义函数
void hello() {
    printf("Hello, World!\n");
}

Running the above code will yield the following output:

Hello, World!

In the above example, the function prototype void hello(); is first declared, followed by the declaration of a function pointer void (*funcPtr)(); in the main() function, which is then assigned the address of the hello function. Lastly, the hello function is called by executing (*funcPtr)();.

bannerAds