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?

有帮助吗?

解决方案

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.

其他提示

You can also define fun as void fun(void* opaque);. This is however not considered a good practice as declaring the parameter as void* will strip it down of any type information. You will also need to interpret the parameter passed, as you will end up with a pointer to a sequence of bytes. You will have to pass the size of the structure somehow too.

This practice is common in the WIN32 API, where you have a field in the structure that specifies the size of the structure (usually named dwSize or similar). This can also help conveying information about the version of the structure definition.

Another thing to consider here is structure packing, which is compiler- and platform-dependent.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top