Advertisement
math230

Callback and function pointers

Jun 25th, 2020
1,402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.79 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. #include<math.h>
  5.  
  6. int x = 3;  //global variable
  7.  
  8. int getNextRandomValue(void);
  9. void populate_array(int *array, size_t arraySize, int (*getNextValue)(void));
  10.  
  11. int main()
  12. {
  13.     int c = 1;
  14.     float a=3.1, b=3.5;
  15.     int myarray[10];
  16. //    populate_array(myarray, 10, getNextRandomValue);  //option
  17.    populate_array(myarray, 10, &getNextRandomValue);
  18.     printf(" myarray[2] is %d \n", myarray[2]);
  19.  
  20.     return 0;
  21. }
  22.  
  23. int getNextRandomValue(void){
  24.     return rand()%100;
  25. }
  26.  
  27. //option
  28. //void populate_array(int *array, size_t arraySize, int (*getNextValue)(void)){
  29. void populate_array(int *array, size_t arraySize, int getNextValue(void)){
  30.     for (size_t i=0; i<arraySize; i++)
  31.         array[i] = getNextValue();
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement