How Does sizeof(Array) work

后端 未结 5 975
我在风中等你
我在风中等你 2020-11-27 15:42

How does c find at run time the size of array? where is the information about array size or bounds of array stored ?

5条回答
  •  情歌与酒
    2020-11-27 16:03

    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 
    #include 
    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.

提交回复
热议问题