Calloc a Two-Dimensional Array

前端 未结 4 1821
你的背包
你的背包 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:05

    Wrong type for 2-D array - well pointed out by many.

    Different suggested solution.

    When allocating, use the sizeof the variable and not sizeof the type. Less likely to get it wrong - easier to maintain.

    //int * own;
    int **own;
    
    own = calloc(row_count, sizeof *own);
    for (i=0; i<row_count; i++){
      own[i] = calloc(column_count, sizeof *(own[i]));
    }
    
    0 讨论(0)
  • 2021-02-11 11:06

    However, every time I reference own[i][j], I get an error saying that the subscripted value is neither array nor pointer nor vector.

    That's right. own[i] is equivalent to *(own + i), which has type int. You cannot apply the subscript operator to an int.

    Note that what your code appears to be trying to create is not a two-dimensional array, but rather an array of pointers. If that's really what you want then own should have type int **, and you should adjust the first calloc() call accordingly. If you really want dynamic allocation of a 2D array, though, then that would be:

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

    Note that there is no need then to allocate (or free) the rows separately.

    Note also, however, that if you do not ever need to reallocate own before it goes out of scope, if you can assume at least a C99 compiler, and if mem_size is will never be too large then you can do this even more easily via a variable-length array:

    int own[mem_size][3] = {{0}};
    

    No explicit dynamic allocation or deallocation is needed at all in that case, and the initializer can be omitted if unneeded. (I include the initializer because calloc() performs equivalent initialization of the allocated space.) "Too large" should be interpreted in relation to the array being allocated on the stack.

    0 讨论(0)
  • 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 ) );
    
    0 讨论(0)
  • 2021-02-11 11:29

    Use:

    int ** own; // int**, not int*
    own = calloc(mem_size, sizeof(int*)); //int*, not int
                                          // And remove the explicit cast.
    
    0 讨论(0)
提交回复
热议问题