How to get the size of dynamically allocated 2d array

前端 未结 4 1826
余生分开走
余生分开走 2021-01-17 06:07

I have dynamically allocated 2D array. Here is the code

int **arrofptr ;
arrofptr = (int **)malloc(sizeof(int *) * 2);
arrofptr[0] = (int *)malloc(sizeof(int         


        
4条回答
  •  轮回少年
    2021-01-17 06:34

    The only return value you get from malloc() is a pointer to the first byte of the allocated region (or NULL on failure). There is no portable, standard, way of getting the associated allocation size from such a pointer, so in general the answer is no.

    The C way is to represent arrays and buffers in general with a pair of values: a base address and a size. The latter is typically of the type size_t, the same as the argument to malloc(), by the way.

提交回复
热议问题