我在下面测试一个程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node_t {
int id;
int contents[0];
}node_t;
int
main(int argc, char* argv[])
{
printf("sizeof node_t is: %d\n", sizeof (struct _node_t)); // output: 4
node_t *node = (node_t*)malloc(sizeof(node_t) + sizeof(int) * 3);
printf("sizeof node is: %d\n", sizeof (node)); // output: 8
return 0;
}
Run Code Online (Sandbox Code Playgroud)
并且节点瞬间的大小为8.但是,在malloc函数中,我将额外的3个整数添加到node结构中.为什么节点大小的输出仍然是8?
PS:gcc(GCC)4.6.3 20120306(Red Hat 4.6.3-2)
因为sizeof()是一个返回类型大小的编译时"运算符".它不知道甚至不关心你malloc()ed.
编辑:此外,你在第二次尝试中采用指针的大小:-)你可能意味着在那里使用类似"sizeof(*node)"的东西,它会再次给你"4".
编辑2:这也是为什么你可以做一些像sizeof(*指针)或sizeof(指针 - >元素)的东西,即使'指针'从未被初始化或无效.sizeof()并不关心任何内容,只关注表达式的结果类型.