Home > other >  Set struct field with function pointer in C
Set struct field with function pointer in C

Time:02-23

I'm messing around with C and i would like to simulate a constructor for a class but using C. I've a structure with two fields, one int and a pointer to a function, like this

typedef struct elem {
    int a;
    void (*initVal)(struct elem*);
} element;

The function initVal is the following

void initVal(struct elem* el) {
    el->a = 5;
}

The main idea behind this function is to set the field a of the struct itself to 5. In the main:

int main() {
    element a;
    (a.initVal)(&a);
    printf("%d\n", a.a);

    return 0;
}

My goal i to have printed 5 in the main, but this program throws a runtime error. What is wrong here? Is it possible to call a function pointer to set a field of the structure where it is defined in? Hope this is clear.

CodePudding user response:

You are using an uninitialized pointer in this statement

(a.initVal)(&a)

You need to write

void initVal(struct elem* el) {
    el->a = 5;
}

//...

element a;
a.initVal = initVal;

a.initVal( &a );

Or

element a = { .initVal = initVal };
a.initVal( &a );
  • Related