问题
I'd like to allocate 2D array (square matrix) using memalign
with 16B instead of using just malloc
.
I have
A =(float **) malloc( (*dim) * sizeof(float*));
for ( i = 0 ; i < (*dim) ; i++) {
A[i] = (float*) malloc(sizeof(float)*(*dim));
}
how can I change code above with memalign
.
回答1:
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);
回答2:
What you have here isn't really a 2D matrix, just a 1D array pointing at more 1D arrays.
Do you want something like this instead?
A = (float*) memalign(16, (*dim) * (*dim) * sizeof(float));
This will generate you a 1D array which is dim^2 elements long. This is how 2D arrays are usually used in C/C++ (unless you have a specific reason to use an array of pointers to other arrays).
I assume you wish to feed this array into some DSP function - It is hard to know more without knowing the function you are trying to use.
If you must have access to the array as A[x][y], you could do this:
float *aMemory = (float*) memalign(16, (*dim) * (*dim));
float **A = (float**) malloc(*dim * sizeof(float));
for (i = 0; i < *dim; i++)
{
A[i] = &aMemory[*dim * i];
}
Now you can access the array aMemory through the array of pointers A, as
// A[row][column]
A[0][0] = 0.0f;
A[1][1] = 1.0f;
etc.
来源:https://stackoverflow.com/questions/12596183/how-to-dynamically-allocate-2d-array-thats-16b-aligned