Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sizeof know the size of the operand array?

Tags:

c++

c

sizeof

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.

like image 808
marchinram Avatar asked Aug 26 '10 20:08

marchinram


People also ask

How does sizeof know array size?

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.

How does sizeof operator work?

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.

Which operators is used to determine the size of the operand?

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.

What is sizeof in array?

The sizeof() function returns the number of elements in an array.


2 Answers

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.

like image 132
bta Avatar answered Oct 03 '22 20:10

bta


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.

like image 30
sbi Avatar answered Oct 03 '22 21:10

sbi