Callback Function in C
Level 5279 keystrokes
Defines a higher-order function apply that receives a function pointer and replaces each array element with the result of calling it. Passing double_val doubles {1, 2, 3, 4, 5} and prints 2 4 6 8 10.
C code
// Takes the array, its length and a callback: a pointer to a function int (int)1void apply(int arr[], int len, int (*func)(int)) { // Visits every element2 for (int i = 0; i < len; i++) { // Calls the callback and stores its result back in the same element3 arr[i] = func(arr[i]);4 }5}6 // The callback: returns its argument doubled7int double_val(int x) { return x * 2; }8 // The array to transform9int nums[] = {1, 2, 3, 4, 5};// Passes double_val by name; apply changes nums in place10apply(nums, 5, double_val);// Prints the doubled values: 2 4 6 8 1011for (int i = 0; i < 5; i++) {12 printf("%d ", nums[i]);13}// Ends the output line14printf("\n");Output
2 4 6 8 10
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
;× 10(× 10)× 10,× 9[× 5]× 5{× 5}× 5"× 4+× 4