07. More on memory

Pointer to function

address of a function in memory. Can be used by '*'-ing.

E. g.:

   1 #include <stdio.h>
   2 
   3 int add(int a, int b)
   4 {
   5         return a+b;
   6 }
   7 
   8 int main(int argc, char *argv[]) {
   9         int (*fpointer)(int, int) = add;
  10         printf("%d + %d = %d\n", 10, 20, (*fpointer)(10, 20));
  11         return 0;
  12 }
  1. Create a dummy calculator with 4 arithmetic operators (+, -, *, /), that cyclically reads 3 integers, A, B, and N and prints the result of operation corresponded to N (0 is '+', 1 is '-', 2 is '*' and 3 is '/'). If N is not in the diapason, the program stops

    • Use function pointer array as this:
      •    1 int (*table[])(int, int) = { add, sub, mul, div };
        
  2. Rewrite this to use characters for operators. After character input, you have to search though the massive of struct elements:
    •    1 
         2 struct _pair {
         3         int (*fun)(int, int);
         4         int chr;
         5 };
         6 
         7 struct _pair table[] = { {add, '+'}, {sub, '-'}, {mul, '*'}, {div, '/'}};
         8 
         9   scanf("%d%c%d", &a, &c, &b);
        10 
      
    • Caution: command can be only «a+b», not «a + b»

  3. Add another operation «^» that performs integer power ab

  4. See documentation to find that scanf is returning integer value, equal to the number of items it has actually scanned successfully. Display an error if there are less than 3 variables scanned.

H/W

HSE/ProgrammingOS/Lab_07_MoreOnMemory (последним исправлял пользователь FrBrGeorge 2020-02-19 10:28:36)