c语言sizeof

来源:互联网 发布:云数据库怎么用 编辑:程序博客网 时间:2024/06/10 04:56

c语言的sizeof

更新:2013-07-24

//////////////////////////////////////////////////////////////////////

环境gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2


  0)sizeof的作用


  c99:6.5.3.4:
  The sizeof operator shall not be applied to an expression that has
  function type or an incomplete type, to the parenthesized name of
  such a type, or to an expression that designates a bit-field member.
  The sizeof operator yields the size (in bytes) of its operand,
  which may be an expression or the parenthesized name of a type.

  The size is determined from the type of the operand.


  说sizeof运算符不应运算函数表达式,或者不完整类型,或者位域类型。只
  是规定对类型(表达式返回值的类型,带括号的类型名称指定的类型)所占
  的内存空间以byte为单位来计算。
  总的来说,sizoef是类型的大小计算运算符,sizeof后面跟的表达式或函数

  调用一般没有被运算,因为大多时候是在编译时便执行sizeof计算。



  1)sizeof 结构体类型或共用体类型


  c99:6.5.3.4:

  When applied to an operand that has structure or union type, the
  result is the total number of bytes in such an object, including

  internal and trailing padding.


  操作数其中若有结构体(structure)或共用体(union)时,还包括类型里

  的填充空间,即所得结果为其占内存实际大小。



  2)sizeof 数组类型


  c99:6.5.3.4:

  When applied to an operand that has array type, the result is the

  total number of bytes in the array.


  对于数组(array),sizeof 数组名,结果是数组总体成员的大小。


  提醒:注意作为函数形参声明的数组,其实际类型为指针。


  3)sizeof 函数类型。


  c99:6.3.2.4:

  A function designator is an expression that has function type.
  Except when it is the operand of the sizeof operator or the
  unary & operator, a function designator with type ‘‘function
  returning type’’ is converted to an expression that has type

  ‘‘pointer to function returning type’’.


  这里说当函数表达式被sizeof运算符和&运算符操作时,它的意义就会变成

  一个指向带有返回类型的函数的指针。


  Because this conversion does not occur, the operand of the sizeof
  operator remains a function designator and violates the constraint

  in 6.5.3.4.


  它也说到用sizeof时这个转换并不发生,6.5.3.4说是不应用sizeof去操作函

  数表达式,这里是说函数名并没有被转换成指针并调用函数吧。


  尝试了一下:
  当sizeof fun();时,相当于sizeof fun()的返回类型。
  当sizeof fun;时,值为1。
  当sizeof &fun;时,值为sizeof 指针。

  当sizeof (&fun)();时,值同于sizeof fun()。



  4)sizeof的语法


  对于操作的是表达式,sizeof后的括号是可省的,操作的是类型名称,则规

  定sizeo后的类型要被括号包围(parenthesized)。


 

  5)sizeof的返回值


  同时规定sizeof的返回值为由实现决定的size_t类型(an unsigned

  integer type),被定义在头文件<stddef.h>和其它头文件中。


本博客版权声明点击打开链接