简体   繁体   中英

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. Why the output of node size is still 8?

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. 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.

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. sizeof() doesn't care a thing about the content of anything, it merely looks at the resulting type of the expression.

First: do not cast the return value of malloc() in C .

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. 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.

Since C99, it's possible to get a partial-runtime evaluation of sizeof , see this Wikipedia text . 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. The above would not compile in pre-C99 versions of C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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