How do I get unnamed structs as parameters to a function in C?

While going through this question yesterday, 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 be like fun

? And how can I use this structure as a structure (pointer) in a function fun

?

+3


source to share


2 answers


For alignment purposes, this prototype should work:

void fun(int *x);

      

And of course:

void fun(void *x);

      



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

?

EDIT as requested

6.7.2.1 - 15

A pointer to a struct object, appropriately transformed, points to its initial member (or, if that member is a bit-field, which it resides), and vice versa. There may be an unnamed addition inside the structure object, but not at the beginning.

+4


source


You can also define fun

how void fun(void* opaque);

. However, this is not considered good practice, since declaring a parameter as void*

would strip it of the type information. You will also need to interpret the passed parameter, since you will receive a pointer to a sequence of bytes. You will also need to pass in the size of the structure.

This practice is common in WIN32 APIs where you have a field in the structure that determines the size of the structure (usually called dwSize or similar). It can also help convey the version information of the structure definition.



Another thing we'll look at is wrapping the structure , which is compiler and platform dependent.

+1


source







All Articles