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条回答
啃猪蹄的小仙女
2楼-- · 2019-04-07 23:48

Nope, the struct doesn't have to add anything. Unlike in Java or .NET, where classes (and structs) have a bunch of other responsibilities, in C and C++, they are simply containers used to hold a number of data members. In C++, they may have to store a vtable to resolve virtual function calls if any exist, but in general, no, a struct itself has no overhead.

The one exception is this:

typedef struct {} empty;
assert(sizeof(empty) > 0);

The size of an empty struct will not be zero. A struct has to have some nonzero size since every object has to have a unique address. (Otherwise you wouldn't be able to create an array of these structs)

查看更多
登录 后发表回答