Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointer To Anonymous Struct

Tags:

c

Is there a way to get a pointer to an anonymous struct? With out anonymous structs I could write the following:

struct a{
    int z;
};
struct b{
    int y;
    struct a *x;
}

This works fine, but I only use struct a within struct b and it seems redundant to pollute the global namespace with it. Is there a way I could define a pointer (x) to an anonymous struct. Something that would probably look like the following:

struct b{
    int y;
    struct {
        int z;
    } *x;
}

Or is this valid on its own?

like image 678
brenden Avatar asked Nov 08 '18 08:11

brenden


1 Answers

Yes you can do this. But there is a complication: there is no way to directly declare another pointer to same type - or an object of that type, because... the struct type is anonymous.

It is still possible to use it however, by allocating memory for it with malloc, as conversions from void * to any pointer to object are possible without an explicit cast:

struct b {
    int y;
    struct {
        int z;
    } *x;
} y;

y.x = malloc(sizeof *y.x * 5);

Why would you think that this is better than polluting the namespace is beyond my imagination.


GCC provides the typeof so you can increase insanity by things like

typeof(y.x) foo;

or even declare a structure of that type

struct b y;
typeof(y.x[0]) foo;
foo.z = 42;
y.x = &foo;
like image 172