代码之家  ›  专栏  ›  技术社区  ›  DJames

试图分配一个连续的内存块并使用3个索引访问它,但是我的方法失败了。

  •  0
  • DJames  · 技术社区  · 8 年前

    我正在尝试编写一个过程,该过程允许我分配大小为n1*n2*n3的连续内存块,并使用3个索引访问它,就像使用数组一样

    int array[n1][n2][n3];
    

    我已经成功地(据我所知)用两个索引管理了这个(见下面的示例)

    #include <stdlib.h>
    
    int main() {
    
        // Dimensions
        const int n1 = 2;
        const int n2 = 2;
    
        int **array;
    
        // Pointers
        array = (int **)malloc(n1*sizeof(int *));
    
        // Contiguous chunk of memory of size n1xn2
        array[0] = (int *)malloc(n1*n2*sizeof(int));
    
        // Pointer arithmetic
        for(int i=0;i<n1;i++) {
            array[i] = array[0] + i*n2;
        }
    
        array[0][0] = 1;
    
        return EXIT_SUCCESS;
    }
    

    但是当我用三个索引尝试类似的构造时,我的过程会抛出一个segfault:

    #include <stdlib.h>
    
    int main() {
    
        // Dimensions
        const int n1 = 2;
        const int n2 = 2;
        const int n3 = 2;
    
        int ***array;
    
        // Pointers
        array = (int ***)malloc(n1*sizeof(int **));
        array[0] = (int **)malloc(n1*n2*sizeof(int *));
    
        // Contiguous chunk of memory of size n1xn2xn3
        array[0][0] = (int *)malloc(n1*n2*n3*sizeof(int));
    
        // Pointer arithmetic
        for(int i=0;i<n1;i++) {
            for(int j=0;j<n2;j++) {
                array[i][j] = array[0][0] + i*n2*n3 + j*n2;
            }
        }
    
        array[0][0][0] = 1;
    
        return EXIT_SUCCESS;
    }
    

    我知道还有其他方法来管理连续的内存块。我特别感兴趣的是为什么我的逻辑在上述情况下失败了。

    2 回复  |  直到 8 年前
        1
  •  1
  •   j123b567    8 年前

    你可能失踪了

    array[i] = array[0] + i*n2;
    

    这是你的密码

    #include <stdlib.h>
    
    int main() {
    
        // Dimensions
        const int n1 = 2;
        const int n2 = 2;
        const int n3 = 2;
    
        int ***array;
    
        // Pointers
        array = (int ***)malloc(n1*sizeof(int **));
        array[0] = (int **)malloc(n1*n2*sizeof(int *));
    
        // Contiguous chunk of memory of size n1xn2xn3
        array[0][0] = (int *)malloc(n1*n2*n3*sizeof(int));
    
        // Pointer arithmetic
        for(int i=0;i<n1;i++) {
            array[i] = array[0] + i*n2;
            for(int j=0;j<n2;j++) {
                array[i][j] = array[0][0] + i*n2*n3 + j*n2;
            }
        }
    
        array[0][0][0] = 1;
    
        return EXIT_SUCCESS;
    }
    
        2
  •  -1
  •   purec    8 年前

    为3D阵列分配内存。 也许我做错了什么,但看起来还可以。

    #include <stdlib.h>
    #include <stdio.h>
    
    int
    main () {
     int n1 = 2;
     int n2 = 3;
     int n3 = 4;
     int i, j;
    
     int ***array;
    
     array = malloc(n1 * sizeof(int**));
    
     for (i = 0; i < n1; i++)
        array[i] = malloc(n2 * sizeof(int*));
    
     for (i = 0; i < n1; i++)
     for (j = 0; j < n2; j++)
        array[i][j] = malloc(n3 * sizeof(int));
    
    
     array[1][2][3] = 15000;
     printf("%d\n", array[1][2][3]);
    
    return 0;
    }