malloc in C, but use multi-dimensional array syntax

后端 未结 8 1003
失恋的感觉
失恋的感觉 2020-12-04 22:59

Is there any way to malloc a large array, but refer to it with 2D syntax? I want something like:

int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICV         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 23:36

    The compiler and runtime have no way of knowing your intended dimension capacities with only a multiplication in the malloc call.

    You need to use a double pointer in order to achieve the capability of two indices. Something like this should do it:

    #define ROWS 400
    #define COLS 200
    
    int **memory = malloc(ROWS * sizeof(*memory));
    
    int i;
    for (i = 0; i < ROWS; ++i)
    {
        memory[i] = malloc(COLS * sizeof(*memory[i]);
    }
    
    memory[20][10] = 3;
    

    Make sure you check all your malloc return values for NULL returns, indicating memory allocation failure.

提交回复
热议问题