2
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.

0

3 Answers 3

4
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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

did you mean .del = delFunc .p = print ?
@waffles Yes, exactly, sorry
is that a C99 or C11 standard notation?
@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.
@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).
|
2

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

2 Comments

will I need to create a variable type of Foo? i.e Foo foo; foo.del = delFunc
What is Return?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.