How does c find at run time the size of array? where is the information about array size or bounds of array stored ?
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.
It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
The size of any pointer is always 8 on your platform, so it's platform dependent. The sizeof operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.
If you have an array then sizeof(array) returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element ( sizeof(array[0]) ). This gives you number of elements in the array.
sizeof(array)
is implemented entirely by the C compiler. By the time the program gets linked, what looks like a sizeof()
call to you has been converted into a constant.
Example: when you compile this C code:
#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { int a[33]; printf("%d\n", sizeof(a)); }
you get
.file "sz.c" .section .rodata .LC0: .string "%d\n" .text .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $164, %esp movl $132, 4(%esp) movl $.LC0, (%esp) call printf addl $164, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.1.2 (Gentoo 4.1.2 p1.1)" .section .note.GNU-stack,"",@progbits
The $132
in the middle is the size of the array, 132 = 4 * 33. Notice that there's no call sizeof
instruction - unlike printf
, which is a real function.
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