This may be a stupid question but how does the sizeof operator know the size of an array operand when you don\'t pass in the amount of elements in the array. I know it does
The problem underlying your trouble to understand this might be because you are confusing arrays and pointers, as so many do. However, arrays are not pointers. A double da[10]
is an array of ten double
, not a double*
, and that's certainly known to the compiler when you ask it evaluate sizeof(da)
. You wouldn't be surprised that the compiler knows sizeof(double)
?
The problem with arrays is that they decay to pointers to their first elements automatically in many contexts (like when they are passed to functions). But still, array are arrays and pointers are pointers.
Sizeof can only be applied to completely defined types. The compiler will either be able to determine the size at compile time (e.g., if you had a declaration like int foo[8];), or it will be able to determine that it has to add code to track the size of a variable-length array (e.g., if you had a declaration like int foo[n+3];).
Contrary to other answers here, note that as of C99, sizeof() is not necessarily determined at compile time, since arrays may be variable-length.
Sizeof is always evaluated at compile time. In multi pass compiler while generating the symbol table compiler must determine the size of each symbol declared to proceed further to generate intermediate code. So for all sizeof referrences in the code replaces the exact value. At intermediate code generation stage all the operators,statements are converted to right intermediate code (ASM/other format). Finally, m/c code generation stage it converts it to the machine code.
Some discussions seen above w.r.t the dynamic allocations relating to sizeof is not in the context at all. Any reference to size(*p) where p is a pointer of any data type , compiler just finds out the data type of *p and replaces its size , not go to check the MCB header of the allocated block to see what is the allocated memory size. It is not at run time. For example double *p; sizeof(*p) can still be done without allocating any memory for pointer p. How is it possible?
sizeof
is interpreted at compile time, and the compiler knows how the array was declared (and thus how much space it takes up). Calling sizeof
on a dynamically-allocated array will likely not do what you want, because (as you mention) the end point of the array is not specified.
sizeof
is usually evaluated at compile time. The notable exception is C99's variable length arrays.
int main(int argc, char **argv)
{
if (argc > 1)
{
int count = atoi(argv[1]);
int someArray[count];
printf("The size is %zu bytes\n", sizeof someArray);
}
else puts("No");
}
If you're using sizeof
on a local variable, it knows how many elements you declared. If you're using sizeof
on a function parameter, it doesn't know; it treats the parameter as a pointer to the array and sizeof
gives the size of a pointer.