简体   繁体   中英

Set struct field with function pointer in C

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.

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM