I have the following program in C. I use malloc to allocate space for a float array of 2048x2048. I have the pointer to this array and I want to index with array indexes like table[1][2].
I know I could use malloc like this:
float ** table;
table = (float **) malloc(2048*sizeof(float*));
for(i=0;i<2048;i++)
table[i]=(float *) malloc(2048*sizeof(float));
//now table[1][2] works just perfect
But I prefer to malloc a solid piece of memory and that's why I used a struct that contains the required table.
#include <stdio.h>
#include <stdlib.h>
struct ftable
{
float table[2048][2048];
};
typedef struct ftable ftable;
int main(void)
{
ftable * A_table;
A_table = (ftable *)malloc(sizeof(ftable));
if (!A_table)
{
puts("Error allocating memory...");
exit(1);
}
float * A;
A = (float *)A_table;
float ** B;
B = (float **)A_table;
//I want to access A[1][2]
//------------ 1st way -------------- works ok
A[1 * 10 + 2] = 5.0;
//or
*(A + 12) = 5.0;
//------------ 2nd way -------------- doesn't work
B[1][2] = 5.0;
//finish
free(A_table);
getchar();
return 0;
}
I want to index the array this way: A[i][j] and not like A[i*columns + j] because later I'm going to use openmp to optimize some for loops and normal array indexing is required. I'm stuck here and I need your help.