How to get the size of dynamically allocated 2d ar

2019-02-21 06:23发布

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

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

Now i have to know that how many bytes are allocated in arrofptr,arrofptr[0],arrofptr[1]? is there any way to know the size?

if we will print

sizeof(arrofptr);
sizeof(arrofptr[0]);
sizeof(arrofptr[1]);

then it will print 4.

4条回答
看我几分像从前
2楼-- · 2019-02-21 06:46

if you want to keep track of the size of an allocated block of code you would need to store that information in the memory block that you allocate e.g.

// allocate 1000 ints plus one int to store size

int* p = malloc(1000*sizeof(int) + sizeof(int)); 
*p = (int)(1000*sizeof(int));
p += sizeof(int);

...

void foo(int *p)
{
  if (p)
  {
    --p;
    printf( "p size is %d bytes", *p );
  }
}

alt. put in a struct

struct
{
  int size;
  int *array;
} s;
查看更多
狗以群分
3楼-- · 2019-02-21 06:56

You can't find size of arrofptr, because it is only a pointer to pointer. You are defining an array of arrays using that. There's no way to tell the size information with only a pointer, you need to maintain the size information yourself.

查看更多
狗以群分
4楼-- · 2019-02-21 06:59

You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.

In your test case above sizeof is returning the size of the pointer, and thus your calculation the size of the pointers is usually 4, this is why you got 4 and is likely to have the trivial result of 4, always.

查看更多
Rolldiameter
5楼-- · 2019-02-21 07:03

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.

查看更多
登录 后发表回答