Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Initialize structs as pointers only?

Tags:

c

struct

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
like image 601
Lemmons Avatar asked Dec 01 '13 04:12

Lemmons


1 Answers

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.

like image 106
Carl Norum Avatar answered Sep 29 '22 17:09

Carl Norum