I know that this question has been asked before, but my question is more specific, here is the code:
#include <stdio.h>
#include <time.h> /* must be included for the time function */
main()
{
time_t t = time(NULL);
srand((unsigned) t);
int i = rand();
int a[i];
printf("%d\n", i); /* ouptut: 18659 */
printf("%d\n", sizeof a); /* output: 74636 */
}
I compiled this code using gcc and -ansi option to restrict it to recognize the ANSI C only. I know that there is no way that the compiler could know at compile-time the size of the array because it's determined randomly at run-time. Now my question is is the value returned by sizeof is just a random value, or it has a meaning?
The sizeof
operator is evaluated at compile time for most operands. In the case of a VLA, it is evaluated at runtime.
From section 6.5.3.4 of the C standard:
2 The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant
So the size returned by sizeof
is the size in bytes of the VLA. In your example, that would be i * sizeof(int)
The value returned by sizeof
is a pseudo-random value that has a meaning:
a
, in bytesrand
.It appears that sizeof(int)
on your system is 4, because the number returned by sizeof
is four times the number of elements in the array.
Note: One of the consequences of allowing VLAs in C99 is that sizeof
is no longer a purely compile-time expression. When the argument of sizeof
operator is a VLA, the result is computed at run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With