Can you write an example of how function pointers work in C?
- User
Can you write an example of how function pointers work in C?
Assistant
Sure! Here's an example to illustrate how function pointers work in C:
#include <stdio.h> // Function to be pointed to int add(int a, int b) { return a + b; } // Function to demonstrate function pointers void functionPointerExample(int (*funcPtr)(int, int)) { int result = funcPtr(5, 10); printf("Result: %d\n", result); } int main() { // Use the address-of operator (&) to get the address of the add function int (*addPtr)(int, int) = &add; // Call the functionPointerExample function and pass the address of the add function functionPointerExample(addPtr); // Call the add function directly int result = add(15, 20); printf("Result: %d\n", result); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.