How Does sizeof(Array) work
How does c find at run time the size of array? where is the information about array size or bounds of array stored ?
Solution 1:
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.
Solution 2:
sizeof is pure compile time in C++ and C prior to C99. Starting with C99 there are variable length arrays:
// returns n + 3
int f(int n) {
char v[n + 3];
// not purely a compile time construct anymore
return sizeof v;
}
That will evaluate the sizeof
operand, because n
is not yet known at compile time. That only applies to variable length arrays: Other operands or types still make sizeof compute at compile time. In particular, arrays with dimensions known at compile time are still handled like in C++ and C89. As a consequence, the value returned by sizeof
is not a compile time constant (constant expression) anymore. You can't use it where such a value is required - for example when initializing static variables, unless a compiler specific extension allows it (the C Standard allows an implementation to have extensions to what it treats as constant).