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.
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.
alt. put in a struct
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.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.
The only return value you get from
malloc()
is a pointer to the first byte of the allocated region (orNULL
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 tomalloc()
, by the way.