Home > Net >  How to dynamically allocate 2D array of pointer that's 64B aligned using posix_memalign
How to dynamically allocate 2D array of pointer that's 64B aligned using posix_memalign

Time:10-22

I have two arrays, y_train which is a 1D array, and x_train which is a 2D array. I need to dynamically allocate these two arrays using posix_memalign. I did that for y_train correctly. where I convert int y_train[4344] into the following code.

   int* Y_train;
posix_memalign((void**)(&Y_train), 64, sizeof(int) * 4344);

Now, I want to convert int x_train[4344][20]; in the same way but not sure how.

CodePudding user response:

Get a memory block of the complete size and assign it to a pointer of the correct type:

void *ptr;
posix_memalign(&ptr, 64, sizeof(int) * 4344);
int *Y_train = (int*)ptr;
posix_memalign(&ptr, 64, sizeof(int) * 20 * 4344);
int (*x_train)[20] = (int (*)[20])ptr;

Now the whole 2D array is correct aligned, but not all inner arrays are correct aligned, because the 20 * sizeof(int) is not a multiple of 64.

When you need every inner array of 20 ints to be aligned correctly, you have to add padding bytes, 12 ints, then every inner array has 128 bytes.

posix_memalign(&ptr, 64, sizeof(int) * 32 * 4344);
int (*x_train)[32] = (int (*)[32])ptr;

Just ignore the last 12 ints.

  • Related