How do I work with dynamic multi-dimensional arrays in C?

前端 未结 9 1606
庸人自扰
庸人自扰 2020-11-22 05:14

Does someone know how I can use dynamically allocated multi-dimensional arrays using C? Is that possible?

9条回答
  •  长情又很酷
    2020-11-22 06:05

    Here is working code that defines a subroutine make_3d_array to allocate a multidimensional 3D array with N1, N2 and N3 elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k] to access its elements.

    #include 
    #include 
    #include 
    
    
    // Method to allocate a 2D array of floats
    float*** make_3d_array(int nx, int ny, int nz) {
        float*** arr;
        int i,j;
    
        arr = (float ***) malloc(nx*sizeof(float**));
    
        for (i = 0; i < nx; i++) {
            arr[i] = (float **) malloc(ny*sizeof(float*));
    
            for(j = 0; j < ny; j++) {
                arr[i][j] = (float *) malloc(nz * sizeof(float));
            }
        }
    
        return arr;
    } 
    
    
    
    int main(int argc, char *argv[])
    {
        int i, j, k;
        size_t N1=10,N2=20,N3=5;
    
        // allocates 3D array
        float ***ran = make_3d_array(N1, N2, N3);
    
        // initialize pseudo-random number generator
        srand(time(NULL)); 
    
        // populates the array with random numbers
        for (i = 0; i < N1; i++){
            for (j=0; j

提交回复
热议问题