1
votes

Given the following struct

struct foo
{
  int b;
  int a;
  int r;
};

I want to create a new type from this struct, like following

typedef struct foo * foo_t;

That is to say that foo_t is supposed to equal a pointer of struct foo.
So struct foo *var; <=> foo_t var;

Why am I not able to malloc this struct from its type?

foo_t var = malloc(sizeof(*foo_t)); throws an error at the compilation time

error: expected expression before foo_t
foo_t var = malloc(sizeof((*_foo_t)));

2
foo_t equals to a pointer. we need to malloc the size of the struct, not the pointer - Romeortec
thanks to everyone - Romeortec
... and this is exactly why I don't like hiding pointers behind typedefs. :-) - melpomene
I'm making oriented object C, I prefer to force to use pointers ;) - Romeortec
I don't think what I'm doing is that bad: gist.github.com/Romain-P/dd16dd4f1102c36d170c5e41d989c6b9 - Romeortec

2 Answers

8
votes

Because sizeof's operand must be either an expression or a parenthesized type name. *foo_t is neither.

I strongly recommend against hiding pointers behind typedefs. However, you can do the following:

foo_t var = malloc(sizeof *var);

var is not a type, so *var is a valid expression.

0
votes

You must alloc a portion of memory of size sizeof(struct foo) for a variable with type foo_t and not of size sizeof(*foo_t). With the function malloc you alloc a portion of memory (of a determinate input size) that the pointer points to. Your variable var is type foo_t, that is, a pointer to a struct foo structure. So the correct syntax for the allocation of variable var is:

foo_t var=malloc(sizeof(struct foo));