Suppose I have a flat, dynamically allocated 1d array (let's call it vector) that will contain some 3d data. Is there any way to create another pointer (let's call it tensor) that would "see" vector as 3d array, so I can access it as tensor[i][j][k]?
I tried the following, but it doesn't work:
int x, y, z; //Number of rows, cols, ...
double *vector;
double ***tensor;
x = 10; y = 10; z = 10;
vector = (double *) malloc(x * y * z * sizeof(double));
tensor = (double ***) vector;
tensor[0] = (double **) vector;
tensor[0][0] = (double *) vector;
for(j = 1; j < y; j++) {
tensor[0][j] = tensor[0][j-1] + z;
}
for(i = 1; i < x; i++) {
tensor[i] = tensor[i - 1] + y;
tensor[i][0] = tensor[i - 1][0] + y * z;
for(j = 1; j < y; j ++) {
tensor[i][j] = tensor[i][j - 1] + z;
}
}
tensor[0][0][0] = 1.0; //Segfaults here
tensor[0][0][1] = 2.0;
...
What am I doing wrong?
I can give you example of allocating 2d array as array of pointers plus 1d array of data In one malloc
const int M = 100;
const int N = 200;
int **a = NULL;
int i, j;
a = malloc(M * sizeof(int*) + N * M * sizeof(int));
a[0] = (int*)(a + M);
for (i = 1; i < M; i++) {
a[i] = a[0] + i * N;
}
//some code
free(a);
An image

And in two mallocs
const int M = 100;
const int N = 200;
int **a = NULL;
int i;
a = malloc(M * sizeof(int*));
a[0] = malloc(M * N * sizeof(int));
for (i = 1; i < M; i++) {
a[i] = a[0] + i * N;
}
//Some code
free(a[0]);
free(a);
An Image

Here are 2 benefits: 1st - quick allocation, second - a[0] is the beginning of 1d array, so you can treat it as 1d. And yes - I'm too lazy to post full solution for 3d array.
You have to allocate memory for the pointers to pointers that are stored in tensor. tensor is a pointer to pointer-to-pointer, so it needs memory for all pointers to pointers that you are allocating.
example:
double*** tensor = new double**[10]; // 10 double pointers are allocated
Similarly for next inner dimension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With