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

前端 未结 9 1608
庸人自扰
庸人自扰 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:09

    Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

    double (*A)[n] = malloc(sizeof(double[n][n]));
    

    and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

    free(A);
    

    Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

    0 讨论(0)
  • 2020-11-22 06:10

    There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:

    int** array;
    array = (int**)malloc(sizeof(int*) * 50);
    for(int i = 0; i < 50; i++)
        array[i] = (int*)malloc(sizeof(int) * 50);
    

    Of course, you can also declare the array as int* array[50] and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.

    It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)], then malloc a block of 50*50 ints or whatever and access using that L macro, e.g.

    #define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
    
    int dim_x = 50;
    int dim_y = 50;
    
    int* array = malloc(dim_x*dim_y*sizeof(int));
    
    int foo = L(array, 4, 6, dim_x);
    

    But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.

    0 讨论(0)
  • 2020-11-22 06:17
    int rows, columns;
    /* initialize rows and columns to the desired value */
    
        arr = (int**)malloc(rows*sizeof(int*));
            for(i=0;i<rows;i++)
            {
                arr[i] = (int*)malloc(cols*sizeof(int));
            }
    
    0 讨论(0)
提交回复
热议问题