Allocate a 2d array in C with one dimension fixed

前端 未结 3 1740
野趣味
野趣味 2021-01-14 15:31

I want to dynamically allocate 1 dimension of a 2D array (the other dimension is given). Does this work:

int NCOLS = 20;

// nrows = user input...

double *a         


        
3条回答
  •  无人共我
    2021-01-14 16:30

    An example:

    #include 
    #include 
    
    #define COLS 2
    
    void func(int (**arr)[COLS], int rows)
    {
        int i, j;
    
        *arr = malloc(sizeof(int[COLS]) * rows);
        printf("Insert number: \n"); 
        for(i = 0; i < rows; i++) 
            for(j = 0; j < COLS; j++) 
                scanf("%d", &(*arr)[i][j]);
        for(i = 0; i < rows; i++) 
            for(j = 0; j < COLS; j++) 
                printf("%d\n", (*arr)[i][j]);
    }
    
    
    int main(void)
    { 
        int (*arr)[COLS];
    
        func(&arr, 2);
        free(arr);
        return 0;
    } 
    

提交回复
热议问题