[英]Using struct pointers in C even if they are not declared
#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;
}
Why the above segment of code compiles (in gcc) and works without problem while I have not defined the foo struct? 为什么在我未定义foo结构的情况下,上述代码段可以编译(在gcc中)并且可以正常工作?
because in your code snippet above, the compiler doesn't need to know the size of struct foo
, just the size of a pointer to struct foo
, which is independent of the actual definition of the structure. 因为在上面的代码段中,编译器不需要知道
struct foo
的大小,而只需知道指向 struct foo
的指针的大小即可,该大小与struct foo
的实际定义无关。
Now, if you had written: 现在,如果您写过:
struct foo *t = malloc(sizeof(struct foo));
That would be a different story, since now the compiler needs to know how much memory to allocate. 那将是另一回事,因为现在编译器需要知道要分配多少内存。
Additionally, if you at an point you try to access a member of a struct foo*
(or dereference a pointer to a foo): 另外,如果您尝试访问
struct foo*
的成员(或取消引用foo的指针),请执行以下操作:
((struct foo*)t)->x = 3;
The compiler would also complain, since at this point it needs to know the offset into the structure of x
. 编译器也会抱怨,因为此时它需要知道
x
结构的偏移量。
As an aside, this property is useful to implement an Opaque Pointer . 顺便说一句,此属性对于实现Opaque Pointer很有用。
"And what about free(t)? Can the compiler free the memory without knowing the real size of the struct?" “那么free(t)呢?编译器可以在不知道结构实际大小的情况下释放内存吗?” No, compiler doesn't free anything.
不,编译器不会释放任何东西。 Free() is just a function with input parameter void *.
Free()只是具有输入参数void *的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.