The sizeof
operator works at compile time, except for the case when the operand is variable length array, and the dynamic memory allocation is run time operation.
In the expression:
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
the type of RandomArray
is int *
and the type of *RandomArray
is int
.
Hence, the expression is equivalent to:
printf("%d %d",sizeof(int *),sizeof(int));
for which the sizeof
will yield the result as an integer constant and therefore, you will get the same result every time irrespective of the size of memory allocate to RandomArray
.
How to find the size of dynamic array
Keep the track of the size from the point where you are allocating memory dynamically.
Beware, you are multiplying the value returned by rand()%11
to the sizeof *RandomArray
while allocating memory and rand()
may return 0
as well which will lead to malloc(0)
. Good to know that (from C Standards#7.22.3):
....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.