Find malloc() array length in C?

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.


If you want to know the size of something you have allocated, then you need to "remember" that yourself, since your code did the allocation. If your code hasn't done the allocation, then there's no way [in a standard sense] to find out how large the memory are a pointer is pointing to. You just have to "know" some other way.


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*).

Tags:

C

Arrays

Malloc