Calloc a Two-Dimensional Array

前端 未结 4 1461
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-11 10:32

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:23

    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 ) );
    

提交回复
热议问题