Calloc a Two-Dimensional Array

前端 未结 4 1815
你的背包
你的背包 2021-02-11 10:40

To make a two dimensional array, I\'m currently using the following:

int * own;

own = (int *)calloc(mem_size, sizeof(int));

for (i=0;i

        
4条回答
  •  一生所求
    2021-02-11 11:10

    Because own is declared as having type int *

    int * own;
    

    then own[i] is a scalar object of type int and you may not apply to it the subscript operator.

    You could write the following way

    int ( *own )[3] = calloc( mem_size, 3 * sizeof( int ) );
    

    The other way is the following

    int **own = malloc( mem_size * sizeof( int * ) );
    
    for ( i = 0; i < mem_size; i++ ) own[i] = calloc( 3, sizeof( int ) );
    

提交回复
热议问题