吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C中的sizeof运算符

C中的sizeof运算符

来源:网络 | 更新时间:2022-01-10 12:58:07
SizeofC 或 C++ 中常用的运算符。它是一个编译时一元运算符,可用于计算其操作数的大小。sizeof 的结果是无符号整数类型,通常用 size_t 表示。sizeof 可以应用于任何数据类型,包括原始类型(如整数和浮点类型)、指针类型或复合数据类型(如结构、联合等 用法 sizeof()运算符根据操作数类型以不同方式使用.  1.当操作数是数据类型时。  sizeof()与 int、float、char 等数据类型一起使用时,它只返回分配给该数据类型的内存量。 让我们看一个例子: 
#include <stdio.h>
int main()
{
printf("%lun", sizeof(char));
printf("%lun", sizeof(int));
printf("%lun", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}
#include <iostream>
using namespace std;

int main()
{
cout << sizeof(char)<<"n";
cout << sizeof(int)<<"n";
cout << sizeof(float)<<"n";
cout << sizeof(double)<<"n";
return 0;
}
输出: 
1
4
4
8
注意: sizeof() 可能会根据机器给出不同的输出,我们已经在 32 位 gcc 编译器上运行了我们的程序。 2.当操作数是表达式时。  sizeof()与表达式一起使用时,它返回表达式的大小。让我们看例子: 
#include <stdio.h>
int main()
{
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 0;
double d = 10.21;
cout << sizeof(a + d));
return 0;
}
输出: 
8
正如我们从 int 和 double 的第一种情况中知道的那样,大小分别为 4 和 8,a 是 int 变量,而 d 是 double 变量。最终结果将是双精度,因此我们程序的输出是 8 个字节。 类型运算符 sizeof() 是一个编译时运算符。编译时间是指将源代码转换为二进制代码的时间。它不执行(运行)()内的代码。让我们看一个例子。
#include <iostream>

using namespace std;
int main() {


int y;

int x = 11;

y = sizeof(x++); //value of x doesn't change

cout<<y<<" "<<x;// prints 4 11

}
如果我们尝试增加 x 的值,它保持不变。这是因为,x 在括号内递增,并且 sizeof() 是编译时运算符。   需要 Sizeof  1.找出数组中元素的数量。  Sizeof 可用于自动计算数组元素的数量。让我们看看例子: 
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 };
printf("Number of elements:%lu ", sizeof(arr) / sizeof(arr[0]));
return 0;
}
#include <iostream>
using namespace std;

int main()
{
int arr[] = { 1, 2, 3, 4, 7, 98,
0, 12, 35, 99, 14 };
cout << "Number of elements: "
<<(sizeof(arr) / sizeof(arr[0]));
return 0;
}
输出: 
Number of elements: 11
2.为了动态分配的内存块。  sizeof 主要用于动态内存分配。例如,如果我们要分配足以容纳 10 个整数的内存,并且我们不知道该特定机器中的 sizeof(int)。我们可以借助 sizeof 进行分配。
int* ptr = (int*)malloc(10 * sizeof(int));
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com