codechaser
V2EX  ›  C

szieof 操作符

  •  
  •   codechaser · Oct 30, 2018 · 4108 views
    This topic created in 2937 days ago, the information mentioned may be changed or developed.

    求教:sizeof 可以返回对象的字节数。

    1

    int array[5] = {0};
    int bytes = sizeof array;
    

    这里的 bytes 等于 20。那么如果定义一个函数:

    2

    void test(int array[]){
        printf("%d\n",sizeof array);
    }
    

    如果传入 array 的话会打印出 4,我刚才看了下书知道这里计算的是 array 这个指针,指针一直为 4 字节,所以会输出 4。那么 1 中 sizeof 也是对 array 这个数组的第一个元素指针操作啊,为什么不输出 4,而输出整个数组的字节数呢?难道sizeof还变吗?它怎么知道传入的是数组还是指针呢?

    18 replies  •  2018-11-01 17:19:08 +08:00
    newmind
    newmind
    Oct 30, 2018 via Android
    1
    标题看的我强迫症犯了
    Franticycea
    Franticycea
    Oct 30, 2018
    2
    @newmind 有点
    chenstack
    chenstack
    Oct 30, 2018
    3
    1 中 array 类型是 int[5],2 中 array 类型是 int[],也就是 int*,所以结果不一样
    zhicheng
    zhicheng
    Oct 30, 2018 via iPhone
    4
    参数里的全是指针。
    GeruzoniAnsasu
    GeruzoniAnsasu
    Oct 30, 2018
    5
    本站已跟百度达成深度合作。。。
    codechaser
    codechaser
    OP
    Oct 30, 2018
    6
    @newmind 我...打错了😂
    bytelee
    bytelee
    Oct 30, 2018
    7
    理解下数组和指针的区别 :)
    fcten
    fcten
    Oct 30, 2018
    8
    数组作为作为函数参数传递时,实际传递的是指针。sizeof 自然只能计算出指针的长度,因为这个时候根本不知道数组的长度。
    chiu
    chiu
    Oct 30, 2018 via Android
    9
    两个 array 类型不一样,一个数组一个指针。
    innoink
    innoink
    Oct 30, 2018 via Android
    10
    int [5]和 int []又不是同一个类型,当然不一样了
    HHehr0ow
    HHehr0ow
    Oct 30, 2018
    11
    sizeof 是一个 compile time 的运算符
    msg7086
    msg7086
    Oct 30, 2018
    12
    sizeof 是编译时运算符,编译完以后的代码是
    int bytes = 20;
    printf("%d\n", 8);
    运行程序并不会改变 8 的值,无论函数的输入是什么样的数组,8 就是 8。
    LGA1150
    LGA1150
    Oct 30, 2018 via Android
    13
    @msg7086 @HHehr0ow
    sizeof 有一个特例是 VLA (变量长度的数组),其大小是在运行时才确定的
    stevenbipt
    stevenbipt
    Oct 30, 2018 via Android
    14
    定义一个指针指向数组
    stevenbipt
    stevenbipt
    Oct 30, 2018 via Android
    15
    然后在 sizeof 那个指针试试←_←
    codechaser
    codechaser
    OP
    Nov 1, 2018
    16
    @stevenbipt 想着指针的指针的指针最后会到哪儿?谁是他们最初的起源呢
    codechaser
    codechaser
    OP
    Nov 1, 2018
    17
    @msg7086 sizeof 返回的值编译的时候就会替换成常量是吗?
    msg7086
    msg7086
    Nov 1, 2018
    18
    @LGA1150 嗷对,还有这新(?)玩意儿……

    @codechaser 如上所说,除开 VLA 以外都是编译时就得出值的。
    至于指针,就只是一个内存地址而已。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1117 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 23:14 · PVG 07:14 · LAX 15:14 · JFK 18:14
    ♥ Do have faith in what you're doing.