GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, May 30, 2011

Function Pointer As Struct Member

Function pointer as struct member - with arguments:

#include <stdio.h>

struct aritmathic{
    int a;
    int b;
    int (*add)(int, int);
    int (*subtract)(int, int);
    int (*multiply)(int, int);
};

int Add(int a, int b){
    return (a+b);
}

int Subtract(int a, int b){
    return (a-b);
}

int Multiply(int a, int b){
    return (a*b);
}

int main(){

    struct aritmathic ar;
    ar.a = 4;
    ar.b = 5;

    ar.add = Add;
    ar.subtract = Subtract;
    ar.multiply = Multiply;

    int a = ar.add(ar.a, ar.b);
    int b = ar.subtract(ar.a, ar.b);
    int c = ar.multiply(ar.a, ar.b);   

    printf("%d\n%d\n%d", a, b, c);

    return 0;
}


Simpler version for above:
#include <stdio.h>

struct aritmathic{
    int a;
    int b;
    int (*add) (struct aritmathic*);
    int (*subtract) (struct aritmathic*);
    int (*multiply) (struct aritmathic*);
};

int Add(struct aritmathic* ar){
    return (ar->a + ar->b);
}

int Subtract(struct aritmathic* ar){
    return (ar->a - ar->b);
}

int Multiply(struct aritmathic* ar){
    return (ar->a * ar->b);
}

int main(){

    struct aritmathic ar;
    ar.a = 4;
    ar.b = 5;

    ar.add = Add;
    ar.subtract = Subtract;
    ar.multiply = Multiply;

    int a = ar.add(&ar);
    int b = ar.subtract(&ar);
    int c = ar.multiply(&ar);   

    printf("%d\n%d\n%d", a, b, c);

    return 0;
}

Share/Bookmark

3 comments:

  1. mas ijin nyuwun backline kita sama sama untung klik di sini

    ReplyDelete
  2. You forgot to add the last \n in your printf statements

    ReplyDelete