typedef struct foo{
void (*del)(void *toDel);
char* (*p)(void *tp)
} Foo;
Foo init(char* (*print)(void*),void (*delFunc)(void*));
Trying to figure out how to assign or initialize the supplied parameters to the struct function pointers.
asked Sep 10, 2017 at 6:36
waffles
911 gold badge2 silver badges7 bronze badges
3 Answers 3
Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted))
{
return Foo{ .del = delFunc, .p = print};
}
What about this? Long form:
Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted))
{
Foo tmp = {
.del = delFunc,
.p = print
};
return tmp;
}
answered Sep 10, 2017 at 6:48
Miroslav Mares
2,4023 gold badges23 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
waffles
did you mean .del = delFunc .p = print ?
Miroslav Mares
@waffles Yes, exactly, sorry
iBug
is that a C99 or C11 standard notation?
Miroslav Mares
@MahonriMoriancumer Yes it is local, but as the return type of the function is
Foo, the tmp variable would be copied to the caller. If, for example, caller executes Foo ptrs_to_fncs = init(ptr1, ptr2);, where ptr1 and ptr2 are appropriate pointers to functions, then the tmp will be copied to the ptrs_to_fncs and therefore no UB. Returning structs in C works similar to returning objects in C++ - they get copied. Of course, the function init() can be rewritten to use dynamically allocated memory instead.Miroslav Mares
@iBug These are designated initializers, introduced to C with the C99 standard, but i. e. with GCC, they can even be used in C89 and C++ as compiler extensions (even though some limitations might apply).
|
How to initialize a struct in accordance with C programming language standards
You can do it the usual way:
Return (Foo){.del=delFunc, .p=print};
4386427
44.7k4 gold badges45 silver badges69 bronze badges
answered Sep 10, 2017 at 6:43
Maarten Arits
1801 silver badge9 bronze badges
The straight forward (most backward compatible approach) to define foo as Foo and initialise it is:
Foo foo = { /* Mind the order of the following initialisers! */
delFunc,
print
};
answered Sep 10, 2017 at 8:48
alk
71.2k10 gold badges112 silver badges274 bronze badges
Comments
lang-c