C语言 - sizeof 运算符



sizeof 运算符是一个编译时一元运算符。它用于计算其操作数的大小,操作数可以是数据类型或变量。它返回以字节为单位的大小。

它可以应用于任何数据类型、浮点类型或指针类型变量。

sizeof(type or var);

当 sizeof() 用于数据类型时,它只是返回分配给该数据类型的内存量。在不同的机器上,输出可能不同,例如,32 位系统显示的输出可能与 64 位系统不同。

示例 1:在 C 语言中使用 sizeof 运算符

请看下面的例子。它突出显示了如何在 C 程序中使用 sizeof 运算符:

#include <stdio.h>

int main(){

   int a = 16;

   printf("Size of variable a: %d \n",sizeof(a));
   printf("Size of int data type: %d \n",sizeof(int));
   printf("Size of char data type: %d \n",sizeof(char));
   printf("Size of float data type: %d \n",sizeof(float));
   printf("Size of double data type: %d \n",sizeof(double));    

   return 0;
}

输出

运行此代码后,您将获得以下输出:

Size of variable a: 4
Size of int data type: 4
Size of char data type: 1
Size of float data type: 4
Size of double data type: 8

示例 2:将 sizeof 与结构体一起使用

在这个例子中,我们声明了一个结构体类型并找到结构体类型变量的大小。

#include <stdio.h>

struct employee {
   char name[10];
   int age;
   double percent;
};

int main(){
   struct employee e1 = {"Raghav", 25, 78.90};
   printf("Size of employee variable: %d\n",sizeof(e1));   
   return 0;
}

输出

运行代码并检查其输出:

Size of employee variable: 24

示例 3:将 sizeof 与数组一起使用

在下面的代码中,我们声明了一个包含 10 个 int 值的数组。对数组变量应用 sizeof 运算符返回 40。这是因为 int 的大小为 4 字节。

#include <stdio.h>

int main(){

   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   printf("Size of arr: %d\n", sizeof(arr));
}

输出

运行代码并检查其输出:

Size of arr: 40

示例 4:使用 sizeof 查找数组的长度

在 C 语言中,我们没有返回数值数组中元素个数的函数(我们可以使用strlen() 函数获取字符串中的字符个数)。为此,我们可以使用sizeof() 运算符。

我们首先找到数组的大小,然后将其除以其数据类型的大小。

#include <stdio.h>

int main(){

   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int y = sizeof(arr)/sizeof(int);

   printf("No of elements in arr: %d\n", y);
}

输出

运行此代码时,它将产生以下输出:

No of elements in arr: 10

示例 5:在动态内存分配中使用 sizeof

sizeof 运算符用于计算要使用malloc()calloc()函数动态分配的内存块。

malloc() 函数使用以下语法

type *ptr = (type *) malloc(sizeof(type)*number);

以下语句分配一个包含 10 个整数的块,并将它的地址存储在指针中:

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

当 sizeof() 用于表达式时,它返回表达式的 size。这是一个例子。

#include <stdio.h>

int main(){

   char a = 'S';
   double b = 4.65;

   printf("Size of variable a: %d\n",sizeof(a));
   printf("Size of an expression: %d\n",sizeof(a+b));

   int s = (int)(a+b);
   printf("Size of explicitly converted expression: %d\n",sizeof(s));

   return 0;
}

输出

运行代码并检查其输出:

Size of variable a: 1
Size of an expression: 8
Size of explicitly converted expression: 4

示例 6:C 语言中指针的大小

sizeof()运算符返回相同的值,而不管类型如何。这包括内置类型、派生类型或双指针指针

#include <stdio.h>

int main(){

   printf("Size of int data type: %d \n", sizeof(int *));
   printf("Size of char data type: %d \n", sizeof(char *));
   printf("Size of float data type: %d \n", sizeof(float *));
   printf("Size of double data type: %d \n", sizeof(double *));
   printf("Size of double pointer type: %d \n", sizeof(int **));
}

输出

运行代码并检查其输出:

Size of int data type: 8
Size of char data type: 8
Size of float data type: 8
Size of double data type: 8
Size of double pointer type: 8
c_operators.htm
广告
© . All rights reserved.