Possible Duplicate:
Aligned memory management?
我有一个数组,我这样声明
int * myarray;
int num_of_element;
myarry = (int*) calloc(num_of_elements, sizeof(int));
int 的大小是 4 个字节,但是我想确保我的数组从 8 个字节边界开始 - 这样我每次都可以有效地加载两个值。有什么不同的方法或其他我可以做的事情吗?
最佳答案
您尝试过posix_memalign
吗?
The function posix_memalign() allocates
size
bytes and places the address of the allocated memory in*memptr
. The address of the allocated memory will be a multiple ofalignment
, which must be a power of two and a multiple ofsizeof(void *)
.
示例:
if (posix_memalign(&myarray, 8, num_of_elements*sizeof(int)) != 0) {
// failed
}
参见http://pubs.opengroup.org/onlinepubs/009696699/functions/posix_memalign.html
Linux posix_memalign 手册页还记录了aligned_alloc() (c11)、memalign()(已过时):
https://www.kernel.org/doc/man-pages/online/pages/man3/posix_memalign.3.html
关于c - 对齐 C 动态内存中数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478628/