即使未声明它们,也在C中使用struct指针

Dra*_*gno 1 c struct pointers

#include <stdlib.h>

struct timer_list
{
};

int main(int argc, char *argv[])
{
  struct foo *t = (struct foo*) malloc(sizeof(struct timer_list));
  free(t);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么上面的代码段编译(在gcc中)并且在我没有定义foo结构时没有问题?

Joh*_*ter 7

因为在上面的代码中你的代码,编译器并不需要知道的大小struct foo,一只是大小的指针struct foo,这是独立于结构的实际定义.

现在,如果你写了:

struct foo *t = malloc(sizeof(struct foo));
Run Code Online (Sandbox Code Playgroud)

这将是一个不同的故事,因为现在编译器需要知道要分配多少内存.

此外,如果您在某一点上尝试访问某个成员struct foo*(或取消引用指向foo的指针):

((struct foo*)t)->x = 3;
Run Code Online (Sandbox Code Playgroud)

编译器也会抱怨,因为此时它需要知道结构的偏移量x.


另外,此属性对于实现不透明指针很有用.

  • ...或`struct foo*t = malloc(sizeof*t);`这是编写此类调用的更安全的方法.最起码,我是这么想的.:) (2认同)