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

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

提交回复
热议问题