Struct's contribution to type size

2019-04-07 23:24发布

I am wondering why the following two types

struct {
    double re[2];
};

and

double re[2];

have the same size in C? Doesn't struct add a bit of size overhead?

7条回答
你好瞎i
2楼-- · 2019-04-07 23:25

No it doesnt.

That's one of the good points of structs (why they were so helpful in old school TCP/IP programming).

It's a good way to represent the memory/buffer layout.

查看更多
别忘想泡老子
3楼-- · 2019-04-07 23:27

No, it just merely composes all the elements into one higher-level element whose size is merely the individual elements' sizes added up (plus some padding depending on alignment rules, but that's out of the scope of this question).

查看更多
▲ chillily
4楼-- · 2019-04-07 23:31
Juvenile、少年°
5楼-- · 2019-04-07 23:33

Not if it can help it - no. C avoids overhead like the plague. And specifically, it avoids overhead in this context.

If you used a different structure, you might see a difference:

struct space_filled
{
    char       part0;
    double     part1;
};

If your machine requires double to be aligned on an 8-byte boundary (and sizeof(double) == 8, which is normal but not mandated by the standard), then you will find that the structure occupies 16 bytes.

查看更多
做自己的国王
6楼-- · 2019-04-07 23:39

No. Struct does not add any size, or have any overhead in the compiled C.

It is a layer of syntax that requires additional work by the compiler, but has no overhead at runtime.

C is an extremely "naked" language, meaning that nothing is there unless required. So ask yourself, "What overhead does a struct REQUIRE?", and you won't find any.

查看更多
再贱就再见
7楼-- · 2019-04-07 23:45

no the struct type in C just sequentially layout the members in memory

查看更多
登录 后发表回答