Search code examples
cstructfunction-prototypesfunction-parameter

How to receive unnamed structures as function parameters in C?


Yesterday while going through this question, I found a curious case of passing and receiving unnamed structures as function parameters.

For example, if I have a structure like this,

int main ()
{
    struct {
        int a;
    } var;

    fun(&var);
}

Now, what should the prototype of fun be? And how can I use that structure as a structure(pointer) in the function fun?


Solution

  • For alignment reasons, this prototype should work:

    void fun(int *x);
    

    And of course:

    void fun(void *x);
    

    I don't see an easy way to actually use the structure effectively in the function; perhaps declare it again inside that function and then assign the void * ?

    EDIT as requested

    6.7.2.1 - 15

    A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.