c - 对齐 C 动态内存中数组的开头

标签 c arrays dynamic-memory-allocation memory-alignment calloc

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 of alignment, which must be a power of two and a multiple of sizeof(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/

相关文章:

c - 在 C 中实现数组列表

c - 尝试仅通过重新排列指针来对链表进行冒泡排序。我的代码有一个我想摆脱的 2 节点列表的解决方法

java - 打印数组显示错误的输出

arrays - 如何在PowerShell中向数组动态添加元素?

C++删除用new分配的char指针

c - 在程序结束时检测到堆栈崩溃

c++ - 缓存行对齐的内存分配会得到返回吗?

c - 如何让指针指向数组中的所有元素?

c - 头文件中没有 extern 的全局变量

javascript - 如何在 JavaScript 中使用特定变量来定位对象