个性化阅读
专注于IT技术分析

c语言中sizeof()操作符

C中通常使用sizeof()运算符。它确定表达式的大小或在char型存储单元数中指定的数据类型。 sizeof()运算符包含单个操作数,该操作数可以是表达式或数据类型转换,其中强制转换是括在括号内的数据类型。数据类型不仅可以是原始数据类型(例如整数或浮点数据类型),而且还可以是指针数据类型和复合数据类型(例如联合和结构)。

需要sizeof()运算符

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

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

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

注意:输出可能在不同的机器上有所不同,例如在32位操作系统上将显示不同的输出,而在64位操作系统上将显示相同数据类型的不同输出。

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

  • 操作数是一种数据类型
  • 操作数是一个表达式

当操作数是数据类型时。

#include <stdio.h>
int main()
{
    int x=89;    // variable declaration.
    printf("size of the variable x is %d", sizeof(x));  // Displaying the size of ?x? variable.
    printf("\nsize of the integer data type is %d", sizeof(int)); //Displaying the size of integer data type.
    printf("\nsize of the character data type is %d", sizeof(char)); //Displaying the size of character data type.

    printf("\nsize of the floating data type is %d", sizeof(float)); //Displaying the size of floating data type.
return 0;
}

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

输出量

当操作数是表达式时

#include <stdio.h>
int main()
{
  double i=78.0; //variable initialization.
  float j=6.78; //variable initialization.
  printf("size of (i+j) expression is : %d", sizeof(i+j)); //Displaying the size of the expression (i+j).
  return 0;
}

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

输出量

size of (i+j) expression is : 8

赞(0)
未经允许不得转载:srcmini » c语言中sizeof()操作符

评论 抢沙发

评论前必须登录!