sizeof(Array) 是如何工作的 [英] How Does sizeof(Array) work

查看:29
本文介绍了sizeof(Array) 是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c 如何在运行时找到数组的大小?关于数组大小或数组边界的信息存储在哪里?

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

推荐答案

sizeof(array) 完全由 C 编译器实现.当程序被链接时,对你的 sizeof() 调用已经被转换成一个常量.

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.

示例:当您编译此 C 代码时:

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));
}

你得到

    .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

中间的$132是数组的大小,132 = 4 * 33.注意这里没有call sizeof指令——不像printf,这是一个真正的函数.

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.

这篇关于sizeof(Array) 是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆