Define functions in structs

You can't really declare stuff inside of a struct in C. This is not C++ or any other OO language where an object encapsulates some kind of scope.

C structs are very simple objects, it's just syntactic sugar for managing a piece of memory. When you create new struct "instance", struct A a;, compiler just reserves stack space according to its size, and when you then do a.member, compiler knows that member's offset, so it jumps to &a + offset of that member. Those offsets are usually not just sums of sizes of preceding members, because compiler usually adds some padding bits into the structure to align it nicer into memory.

Hope it helped a bit. You obviously expect slightly too much from C stuctures :-)


No, as functions are not data. But you can define function pointers inside a struct.

struct foo {
    int a;
    void (*workwithit)(struct foo *);
}

Tags:

C