开发者

Memory alignment (Using C specifically)

If you've got a struct within a struct, say:

struct {
    double a;
    struct {
        char *b[20];
        char c;
    }d;
}开发者_如何转开发e;

will struct e need to start on a multiple of the size of struct d, or a multiple of the size of the largest member of d (char *b[20])?


The struct e will start at whatever alignment is necessary for the members, and the struct as a whole, to be accessible.

That alignment will vary for different implementations.

We know that the alignment for e will be at least as strict as the alignmentf for double and at least as strict as the alignment for e.d -- and the alignment of e.d will be at least as strict as the alignment for its members.

Contrary to the other answers, the alignment of a scalar type is not necessarily the same as its size. For example, it's possible that double might be 8 bytes, but only require 4-byte alignment. Aligning each scalar type (integer, floating-point, pointer) to its full size is fairly common, but it's not universal.

And note that the optimal alignment may be more strict than the required alignment. On the x86, as I understand it, the CPU can access objects on any byte boundary -- but access to properly aligned objects is more efficient. (On other CPUs, misaligned access may require software support.) Compilers will typically align objects for maximum efficiency (but may provide non-standard extensions to save space).

But the alignment for a type cannot exceed its size. For example, you can't have a 3-byte type that requires 4-byte alignment. Arrays cannot have gaps between their elements. (In such a case, the compiler would probably pad the type to 4 bytes; the padding would be part of the object, not inserted between objects.)


It's compiler- and settings-dependent. In most cases will start at the first member's granularity, which in your case is sizeof(char*). Note, that it's not sizeof(char*) * 20, since it's an array and not a native type. Also note that in your case, the struct e will always start at least at granularity of sizeof(double), and therefore struct d will do too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜