Thread: passing function pointer as argument

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    31

    passing function pointer as argument

    hello, so im fiddling with this topic. i don't understand why its running properly in debugger but the output is wrong in the commandline.



    Code:
    #include <stdio.h>
    
    int mul(int a, int b);
    int div(int a, int b);
    int calc(int (*op_ptr)(int, int), int a, int b);
    
    int main(){
        printf("%d", calc(*(&div), 10, 5));
        int (*c_ptr)(int (*a)(int,int), int, int) = calc;
        printf("%d", (*c_ptr)(mul, 210, 5));
    }
    
    
    int mul(int a, int b){
        return a*b;
    }
    
    int div(int a, int b){
        return a/b;
    }
    
    int calc(int (*op_ptr)(int, int), int a, int b){
        return (*op_ptr)(a, b);
    }
    Last edited by thagulf2017; 05-30-2017 at 01:21 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    What do you mean "the output is wrong"?

    Do you see 21050 being printed?

    It might help if you put some newlines in your printf, so you see
    2
    1050
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    31
    Quote Originally Posted by Salem View Post
    What do you mean "the output is wrong"?

    Do you see 21050 being printed?

    It might help if you put some newlines in your printf, so you see
    2
    1050
    thanks it outputs correctly after adding '\n'

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-27-2014, 12:10 AM
  2. Replies: 2
    Last Post: 06-04-2013, 08:25 AM
  3. Passing address or pointer as argument to function
    By Edelweiss in forum C Programming
    Replies: 7
    Last Post: 08-17-2011, 12:38 AM
  4. Replies: 12
    Last Post: 05-24-2011, 05:57 AM
  5. passing pointer argument
    By timhxf in forum C Programming
    Replies: 8
    Last Post: 01-08-2007, 10:38 AM

Tags for this Thread