sizeof(Array)如何工作?

Kaz*_*oom 51 c arrays

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

Dav*_*d Z 64

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));
}
Run Code Online (Sandbox Code Playgroud)

你得到

    .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
Run Code Online (Sandbox Code Playgroud)

$132在中间是阵列的尺寸,132 = 4*33注意,没有call sizeof指令-不像printf,这是一个真正的功能.


Joh*_*itb 19

sizeof是C++之前的纯编译时间和C99之前的C. 从C99开始,有可变长度数组:

// returns n + 3
int f(int n) {
    char v[n + 3];

    // not purely a compile time construct anymore
    return sizeof v;
}
Run Code Online (Sandbox Code Playgroud)

这将评估sizeof操作数,因为n在编译时尚不知道.这适用于可变长度数组:其他操作数或类型仍然在编译时使sizeof计算.特别是,在编译时已知维度的数组仍然像C++和C89一样处理.因此,返回的值sizeof不再是编译时常量(常量表达式).您不能在需要这样的值的地方使用它 - 例如,在初始化静态变量时,除非编译器特定的扩展允许它(C标准允许实现具有对它所处理的常量的扩展).

  • 很高兴您提到C99 VLA.但是,您的答案应该强调,即使在C99中,固定大小的数组在编译时也会计算它们的大小 - 只有VLA在运行时计算其大小.也许,因此,你不能总是在C99中使用'sizeof(array)'作为常量. (4认同)
  • +1 用于区分 C99 中“sizeof”的编译时和非编译时评估,但实际上如何计算可变长度数组的长度?它存储在数组描述符还是其他什么中? (2认同)

Hen*_*man 9

sizeof() 将仅适用于固定大小的数组(可以是静态的,基于堆栈的或在结构中).

如果将它应用于使用malloc(或C++中的新增功能)创建的数组,您将始终获得指针的大小.

是的,这是基于编译时信息.

  • 您已经忘记了C99 VLA - 可变长度阵列. (3认同)

Dan*_*lau 7

sizeof给出变量的大小,而不是你指向的对象的大小(如果有的话.)sizeof(arrayVar)将以字节为单位返回数组大小,当且仅当arrayVar在范围内声明为数组而不是指针时.

例如:

char myArray[10];
char* myPtr = myArray;

printf("%d\n", sizeof(myArray)) // prints 10 
printf("%d\n", sizeof(myPtr)); // prints 4 (on a 32-bit machine)
Run Code Online (Sandbox Code Playgroud)