如何动态分配 16B 对齐的二维数组 [英] How to dynamically allocate 2d array that's 16B aligned
本文介绍了如何动态分配 16B 对齐的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用带有 16B 的 memalign
而不是仅使用 malloc
来分配二维数组(方阵).
I'd like to allocate 2D array (square matrix) using memalign
with 16B instead of using just malloc
.
我有
A =(float **) malloc( (*dim) * sizeof(float*));
for ( i = 0 ; i < (*dim) ; i++) {
A[i] = (float*) malloc(sizeof(float)*(*dim));
}
如何使用 memalign
更改上面的代码.
how can I change code above with memalign
.
推荐答案
使用 malloc()
你需要请求 15 个额外的字节,然后将返回的指针四舍五入到最接近的 16 的倍数,例如:
With malloc()
you need to request 15 extra bytes and then round-up the returned pointer to the nearest multiple of 16, e.g.:
void* p = malloc(size + 15);
void* paligned;
if (!p) { /* handle errors */ }
paligned = (void*)(((size_t)p + 15) / 16 * 16);
/* use paligned */
free(p);
这篇关于如何动态分配 16B 对齐的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文