> For the complete documentation index, see [llms.txt](https://fashaun.gitbook.io/dev-c/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://fashaun.gitbook.io/dev-c/data-type/data-alignment.md).

# Data Alignment

\#Data Alignment

要運算速度快，就需 Data Alignment。要節省記憶體的使用，就取消 Alignment。

32 bit system c/c++ default alignment (in byte)

* char (1 byte): 1- byte aligned (mem 起始位置必須為 1 的倍數)
* short (2 byte): 2 - byte aligned (mem 起始位置必須為 1 的倍數)
* int 4: 4
* float 4: 4
* double 8: 8 (windows), 4 (Linux)
* long double 16
* pointer 4: 4

64 bit (LP64 ) (in byte)

* char 1
* short 2
* int 4
* float 4
* long 8
* long long 8
* double 8:8
* long double 16
* pointer 8:8

sign or unsign will not affect size

如果是使用default alignment, 會產生如下的 padding 效應

Compiler 在 alignment 時最大原則：以目前最大的 alignment size向前 padding，向後 allocate大小.

Ex:

解法 1. **Reorder struct member**

解法 2. **pack pragma**

`#pragma pack(push) // Save original setting`

`#pragma pack(n) // n = The number of byte alignment you want compiler to do`

`struct define_block`

`{`

`......`

`}`

`#pragma pack() //取消 byte alignment`

`#pragma pack(pop) //Back to original setting`

解法 3. use pack as attribute

<https://read01.com/Nyxg0g.html>
