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 doesn't return the total elements in the array but the size in bytes, but to get that it still has to know when the array ends. Just curious as to how this works.
sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value. Again the sizeof(int) or sizeof(pointer) is platform dependent.
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable.
The sizeof() function returns the number of elements in an array.
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.
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.
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