Romeortec
Romeortec

Reputation: 211

C malloc a struct from its typedef

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)));

Upvotes: 1

Views: 1580

Answers (2)

user7185778
user7185778

Reputation:

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));

Upvotes: 0

melpomene
melpomene

Reputation: 85777

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.

Upvotes: 9

Related Questions