Memory alignment of C/C ++ struct (vc6.0)

Source: Internet
Author: User

The compiling environment is vc6.0.

Summary of memory alignment in sizeof (struct:

First, find the type of the largest byte occupied by the entire struct. Assume that the number of bytes occupied by the struct is m, and then add them in the declared order to obtain the number of bytes M. If the total number of bytes of M is less than m, next, let's look at the next byte n. If m + n> m, then n is not calculated, and m is changed to m first, and then calculated from N. (The statement may not be clear enough. Let's look at the example)

(1) first definition method

Struct {

Int;

Char C;

Double B;

};

The result of calling sizeof (a) is 16.

The maximum number of bytes is 8 bytes.

Int type occupies 4 bytes, M = 4, m <8

Char occupies 1 byte, 4 + 1 = 5 <8

The double type occupies 8 bytes, 5 + 8> 8;

Therefore, the five bytes are first aligned to eight bytes.

Then let's look at double, 8 + 8 = 16 bytes.

(2) method 2

Struct B

{

Int;

Char C;

Int D;

Double B;

};

The result of calling sizeof (B) is 24.

Int type occupies 4 bytes, M = 4 <8

Char type, M = 5 <8

Int type, m + n> 8,

Therefore, the first five bytes are first aligned to 8,

Let's look at the int type, which is 4

Double is 8, 4 + 8> 8

Therefore, the memory alignment of 4 bytes is changed to 8 bytes.

Double type, 8 bytes. 8 + 8 + 8 = 24.

(3) third definition method

Struct C

{

Int;

Char C;

Char D;

Double B;

};

The result of sizeof call is 16.

4 <8

4 + 1 <8

4 + 1 + 1 <8

4 + 1 + 1 + 8> 8 + 4 + 1 + 1 = 8

8 + 8 = 16.

(4) fourth definition method

Struct d {

Int;

Double B;

Char C;

};

The result of sizeof call is 24.

4 <8

4 + 8> 8

4 = 8, 8 = 8

1 <8 1 = 8

8 + 8 + 8 = 24.

Welcome to shoot bricks.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.