Take the 2-minute tour ×

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


then it will print 4.

share|improve this question
No - you just have to keep track of this yourself. –  Paul R Sep 28 '12 at 6:34
the size of the pointers is usually 4, this is why you got 4. the bytes which allocated are in the parameter of the malloc(...), in your case these are sizeof(int) * 6144 and sizeof(int) * 4800... ... ... –  holex Sep 28 '12 at 7:15
This is not a 2d array, it is a bunch of segmented arrays with an array of pointers to keep track of them. For info of how to properly allocate 2d arrays dynamically, read this. Also, you should never typecast the result of malloc. –  Lundin Sep 28 '12 at 7:25

3 Answers 3

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.

share|improve this answer

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.

share|improve this answer

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)
    printf( "p size is %d bytes", *p );

alt. put in a struct

  int size;
  int *array;
} s;
share|improve this answer

Your Answer


