Computer >> Máy Tính >  >> Lập trình >> C ++

Làm thế nào để khai báo một con trỏ đến một hàm trong C?

Con trỏ là một biến có giá trị là địa chỉ của một biến hoặc khối bộ nhớ khác, tức là địa chỉ trực tiếp của vị trí bộ nhớ. Giống như bất kỳ biến hoặc hằng số nào, bạn phải khai báo một con trỏ trước khi sử dụng nó để lưu trữ bất kỳ biến hoặc địa chỉ khối nào.

Cú pháp

Datatype *variable_name

Thuật toán

Begin.
   Define a function show.
      Declare a variable x of the integer datatype.
      Print the value of varisble x.
   Declare a pointer p of the integer datatype.
   Define p as the pointer to the address of show() function.
   Initialize value to p pointer.
End.

Đây là một ví dụ đơn giản trong C để hiểu khái niệm con trỏ đến một hàm.

#include
void show(int x)
{
   printf("Value of x is %d\n", x);
}
int main()
{
   void (*p)(int); // declaring a pointer
   p = &show; // p is the pointer to the show()
   (*p)(7); //initializing values.
   return 0;
}

Đầu ra

Value of x is 7.