无涯教程-C语言 - sizeof()

82 阅读2分钟

sizeof()运算符通常在C语言中使用。它确定表达式的大小或在char型存储单元数中指定的数据类型。 sizeof()运算符包含一个操作数,它可以是表达式或数据类型转换,其中强制类型转换是括在括号内的数据类型。

sizeof()运算符

主要是程序知道原始数据类型的存储大小。尽管数据类型的存储大小是恒定的,但在不同平台上实现时,它会有所不同。例如,我们使用 sizeof()运算符动态分配数组空间:

int *ptr=malloc(10*sizeof(int));

在上面的示例中,我们使用了sizeof()运算符,该运算符应用于int类型的转换。我们使用 malloc()函数分配内存,并返回指向该已分配内存的指针。内存空间等于int数据类型占用的字节数并乘以10。

sizeof()运算符的行为根据操作数的类型而有所不同。

  • 操作数是数据类型
  • 操作数是表达式

当操作数是数据类型时。

#include <stdio.h>
int main()
{
    int x=89;   //变量声明。
    printf("size of the variable x is %d", sizeof(x)); // 显示 ?x变量 的大小.
    printf("\nsize of the integer data type is %d",sizeof(int)); //显示 int 数据类型的大小.
    printf("\nsize of the character data type is %d",sizeof(char)); //显示 char 数据类型的大小 
printf</span><span class="pun">(</span><span class="str">"\nsize of the floating data type is %d"</span><span class="pun">,</span><span class="kwd">sizeof</span><span class="pun">(</span><span class="kwd">float</span><span class="pun">));</span><span class="pln"> </span><span class="com">//显示 float 数据类型的大小 <br></span><span class="pln">

return 0; }

在上面的代码中,我们借助于 sizeof()运算符来打印不同数据类型(例如int,char,float)的大小。

sizeof() operator in C

当操作数是表达式时

#include <stdio.h>
int main()
{
  double i=78.0; //变量初始化。
  float j=6.78; 
  printf("size of (i+j) expression is : %d",sizeof(i+j)); //显示表达式的大小 (i+j)。
  return 0;
}

在上面的代码中,我们分别创建了两个类型为double和float的变量i和j,然后使用 sizeof(i + j)运算符打印表达式的大小。

size of (i+j) expression is : 8

参考链接

www.learnfk.com/c-programmi…