Calloc a Two-Dimensional Array

前端 未结 4 1462
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    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.

提交回复
热议问题