将*指针转换为***指针

use*_*579 2 c pointers

假设我有一个平坦的,动态分配的1d数组(我们称之为vector),它将包含一些3d数据.有没有办法创建另一个指针(让我们称之为tensor)"看到" vector为3d数组,所以我可以访问它tensor[i][j][k]

我尝试了以下,但它不起作用:

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;
...
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Iva*_*nov 8

我可以举例说明将2d数组分配为指针数组加上1d数据数组在一个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);
Run Code Online (Sandbox Code Playgroud)

一个图像

在此输入图像描述

并在两个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);
Run Code Online (Sandbox Code Playgroud)

一个图像

在此输入图像描述

这有两个好处:第1个 - 快速分配,第二个 - [0]是1d数组的开头,因此您可以将其视为1d.是的 - 我懒得发布3d阵列的完整解决方案.