简体   繁体   English

零长度数组的结构的大小是多少?

[英]What's the size of a structure with zero length array?

I test a program below: 我在下面测试一个程序:

#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;
}

And the size of node instant is 8. However, in the malloc function, I put extra 3 integers to the node structure. 节点即时的大小为8。但是,在malloc函数中,我在node结构中增加了3个整数。 Why the output of node size is still 8? 为什么输出的节点大小仍然为8?

PS: gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2) PS:gcc(GCC)4.6.3 20120306(Red Hat 4.6.3-2)

Because sizeof() is a compiletime "operator" that returns the size of the type. 因为sizeof()是一个编译时的“运算符”,它返回类型的大小。 It doesn't know or even care what you malloc()ed. 它不知道甚至不在乎您分配的内容。

EDIT: besides, you're taking the size of a pointer in your second try :-) You probably meant to use something like "sizeof(*node)" there, which would have given you "4" again. 编辑:此外,您将在第二次尝试中使用指针的大小:-)您可能打算在那里使用“ sizeof(* node)”之类的东西,这将再次为您提供“ 4”。

EDIT 2: this is also the reason why you can do something like sizeof(*Pointer) or sizeof(Pointer->Element) even if 'Pointer' has never been initialized or is otherwise invalid. 编辑2:这也是为什么即使未初始化“指针”或以其他方式无效的原因,也可以执行诸如sizeof(* Pointer)或sizeof(Pointer-> Element)之类的原因。 sizeof() doesn't care a thing about the content of anything, it merely looks at the resulting type of the expression. sizeof()并不关心任何内容,它只是查看表达式的结果类型。

First: do not cast the return value of malloc() in C . 第一: 不要在C中malloc()的返回值

Second: it's better to not repeat the type name, but instead use the left-hand pointer you're assigning the malloc() :ed pointer to, since it already has the type. 第二:最好不要重复类型名称,而应使用向其分配malloc() :ed指针的左侧指针,因为它已经具有类型了。 Thus: 从而:

node_t *node = malloc(sizeof *node + 3 * sizeof(int));

In this code, the evaluation of the sizeof operator expressions are done at compile-time, and thus there's no information available from the execution of the code. 在此代码中,对sizeof运算符表达式的求值是在编译时完成的,因此从代码执行中没有可用的信息。

Since C99, it's possible to get a partial-runtime evaluation of sizeof , see this Wikipedia text . 从C99开始,可以对sizeof进行部分运行时评估,请参阅Wikipedia文本 The most basic example given is: 给出的最基本的示例是:

size_t flexsize(int n)
{
   char b[n+3];      /* Variable length array */
   return sizeof b;  /* Execution time sizeof */
}

The above requires runtime evaluation of sizeof , since the exact value of n is not constant and not known at compile-time. 上面要求运行时评估sizeof ,因为n的确切值不是恒定的,在编译时也不知道。 The above would not compile in pre-C99 versions of C. 上述内容无法在C99之前的版本中编译。

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

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