简体   繁体   English

C从其typedef中分配一个结构

[英]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 . 也就是说foo_t应该等于struct foo的指针。
So struct foo *var; 所以struct foo *var; <=> foo_t 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之前的预期表达式
foo_t var = malloc(sizeof(( *_ foo_t))); foo_t var = malloc(sizeof(( * * foo_t)));

Because sizeof 's operand must be either an expression or a parenthesized type name. 因为sizeof的操作数必须是表达式或带括号的类型名称。 *foo_t is neither. *foo_t都不是。

I strongly recommend against hiding pointers behind typedefs. 我强烈建议不要将指针隐藏在typedef后面。 However, you can do the following: 但是,您可以执行以下操作:

foo_t var = malloc(sizeof *var);

var is not a type, so *var is a valid expression. var不是类型,因此*var是有效的表达式。

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). 您必须为foo_t类型而不是sizeof(* foo_t)大小的变量分配一部分大小为sizeof(struct foo)的内存。 With the function malloc you alloc a portion of memory (of a determinate input size) that the pointer points to. 使用函数malloc可以分配指针指向的一部分内存(确定的输入大小)。 Your variable var is type foo_t, that is, a pointer to a struct foo structure. 您的变量var是foo_t类型,即指向foo结构的指针。 So the correct syntax for the allocation of variable var is: 因此,分配变量var的正确语法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM