如何动态分配16B对齐的2D数组 [英] How to dynamically allocate 2d array that's 16B aligned

查看:72
本文介绍了如何动态分配16B对齐的2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用带有16B的memalign而不是仅使用malloc来分配2D数组(方阵).

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对齐的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆