#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;
}
为什么上面的代码段编译(在 gcc 中)并且在我没有定义 foo 结构时没有问题?
最佳答案
因为在上面的代码片段中,编译器不需要知道 struct foo
的大小,只需要知道指向 struct foo 的指针 的大小
,它独立于结构的实际定义。
现在,如果你写了:
struct foo *t = malloc(sizeof(struct foo));
那将是另一回事,因为现在编译器需要知道要分配多少内存。
此外,如果您在某个时候尝试访问 struct foo*
的成员(或取消引用指向 foo 的指针):
((struct foo*)t)->x = 3;
编译器也会提示,因为此时它需要知道 x
结构中的偏移量。
顺便说一句,这个属性对于实现 Opaque Pointer 很有用。 .
关于c - 在 C 中使用结构指针,即使它们没有声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14217216/