Re: obj function hello()



gert wrote:
On Feb 9, 1:30 am, Ian Collins <ian-n...@xxxxxxxxxxx> wrote:

You can't have functions in structs in C. What yo can have is function
pointers:

struct Obj {
int someInt;
int (*someFn)(void);

};

But you have to assign a function address to the pointer for each
instance of Obj.


So this means i have to do something like this then ?

#include <stdio.h>

struct obj {
char *data = ''
int (*add)(void);
}

No, you are still assuming C is an OO language. In C you have to be
explicit:

#include <stdio.h>
#include <stdlib.h>

typedef struct Obj {
int value;
int (*add)(struct Obj*,int);
} Obj;

int add( Obj* obj, int val ) {
obj->value += val;
return obj->value;
}

int main(void) {
Obj* obj = malloc( sizeof obj );

obj->value = 0;
obj->add = add;

obj->add( obj, 42 );

printf( "%d\n", obj->value );

return 0;
}

--
Ian Collins.
.



Relevant Pages

  • renee.c
    ... typedef struct AttrString *AttrString; ... Tcl_Obj *Obj; ... int red, green, blue, index; Colour next; ... chars name; ...
    (comp.lang.tcl)
  • Re: Double Linked List test
    ... int main ... boolean test(struct Obj *l, char *value_wanted) ... struct Obj *p_link; ...
    (comp.lang.c)
  • Re: Does malloc() reuse addresses?
    ... So all pointers in the list are always valid. ... struct obj *next; ... void deleteobj{ ...
    (comp.lang.c)
  • Double Linked List test
    ... int main ... boolean test(struct Obj *l, char *value_wanted) ... struct Obj *p_link; ...
    (comp.lang.c)
  • Re: unchecked call to compareTo(T)
    ... Hendrik Maryns wrote: ... Node(T obj) { ... found: int ...
    (comp.lang.java.programmer)