C: Initialize structs as pointers only?

c, struct

Solution

Sure - you just need to hide away the definition of the `struct` into its own translation unit away from prying eyes. Then, someplace else (and more public), just forward declare the structure:

typedef struct x blah;

`blah` in this case is an incomplete type, so anyone with access only to that declaration will only be able to create `blah *` objects, not full `blah` objects.

Another option is to change your typedef:

typedef struct
{
    int foo;
} *blah;

Now, `blah` is inherently a pointer type, and any declaration:

blah b;

Is in fact creating only a pointer. Since the `struct` itself is anonymous, there's no way to create one except through the pointer-only `typedef`.

Problem

Is there a way to ensure a struct object upon creation is always a pointer? ex: ``` typedef struct { int foo; } blah; blah a; // error blah* b; // ok ```

Original source