Find malloc() array length in C? [duplicate] Find malloc() array length in C? [duplicate] arrays arrays

Find malloc() array length in C? [duplicate]


In the second case, num is not an array, is a pointer. sizeof is giving you the size of the pointer, which seems to be 8 bytes on your platform.

There is no way to know the size of a dynamically allocated array, you have to save it somewhere else. sizeof looks at the type, but you can't obtain a complete array type (array type with a specified size, like the type int[5]) from the result of malloc in any way, and sizeof argument can't be applied to an incomplete type, like int[].


Arrays are not pointers (the decay to pointers in some situations, not here).

The first one is an array - so sizeof gives you the size of the array = 40 bytes.

The second is a pointer (irrespective of how many elements it points to) - sizeof gives you sizeof(int*).


The second size refers to the size of a pointer, that, in your machine -- probably 64bits --, is 8 bytes.

You cannot use sizeof() to recover the size of a dynamically allocated structure, but you can do so for statically allocated ones.