gpt4 book ai didi

c - sizeof(Array) 是如何工作的

转载 作者:太空狗 更新时间:2023-10-29 16:18:21 26 4
gpt4 key购买 nike

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

最佳答案

sizeof(array) 完全由 C 编译器实现。当程序被链接时,对您的 sizeof() 调用已转换为常量。

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

#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,这是一个真正的功能。

关于c - sizeof(Array) 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/671790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com