C - sizeof 运算符
sizeof 运算符是一个编译时一元运算符。它用于计算其操作数的大小,操作数可以是数据类型或变量。它返回以字节数表示的大小。
它可以应用于任何数据类型、浮点类型或指针类型变量。
sizeof(type 或 var);
当 sizeof() 与数据类型一起使用时,它仅返回分配给该数据类型的内存大小。输出在不同机器上可能有所不同,例如,32 位系统和 64 位系统可能显示不同的输出。
示例 1:在 C 中使用 sizeof 运算符
请看以下示例。它强调了如何在 C 程序中使用 sizeof 运算符 −
#include <stdio.h> int main(){ int a = 16; printf("Size of variable a: %d ",sizeof(a)); printf("Size of int data type: %d ",sizeof(int)); printf("Size of char data type: %d ",sizeof(char)); printf("Size of float data type: %d ",sizeof(float)); printf("Size of double data type: %d ",sizeof(double)); return 0; }
Output
运行此代码后,您将获得以下输出 -
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
在此示例中,我们声明一个 struct 类型,并计算该结构体类型变量的大小。
#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 ",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 ", 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 ", 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() 与表达式一起使用时,它会返回表达式的大小。以下是示例。
#include <stdio.h> int main(){ char a = 'S'; double b = 4.65; printf("Size of variable a: %d ",sizeof(a)); printf("Size of an expression: %d ",sizeof(a+b)); int s = (int)(a+b); printf("Size of explicitly converted expression: %d ",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 ", sizeof(int *)); printf("Size of char data type: %d ", sizeof(char *)); printf("Size of float data type: %d ", sizeof(float *)); printf("Size of double data type: %d ", sizeof(double *)); printf("Size of double pointer type: %d ", 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