简体   繁体   中英

how to create an aligned array of integers in c++?

My current code is:

a = new int[10];

and the address of a is 0x...040 I want it to be 4096 byte aligned so I tried to change it to:

a = new __declspec(align(4096)) int[10];

but still this doesn't work (the address is still ends with 040 instead of with 000 . What am I doing wrong?

__declspec(align(...)) can be used for static arrays, like:

__declspec(align(4096)) int a[10];

For dynamic allocation use _aligned_malloc function, use _aligned_free to release array allocated by _aligned_malloc :

int* a = (int*) _aligned_malloc(10 * sizeof(int), 4096);
...
_aligned_free(a);

Required include is malloc.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM