Calloc a Two-Dimensional Array

北城以北 提交于 2020-08-01 09:18:09

问题


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<mem_size;i++){
    own[i] = (int *)calloc(3, sizeof(int));
}

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


回答1:


Use:

int ** own; // int**, not int*
own = calloc(mem_size, sizeof(int*)); //int*, not int
                                      // And remove the explicit cast.



回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/29977084/calloc-a-two-dimensional-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!