Sizeof 运算符是 C 语言中最常用的运算符之一,用于计算我们传递的任何数据结构或数据类型的大小。 sizeof 运算符返回无符号整数类型,该运算符可应用于原始数据类型和复合数据类型。我们可以直接对数据类型使用 sizeof 运算符并了解它占用的内存 -
#include <bits/stdc++.h> using namespace std; int main() { cout << sizeof(int) << "\n"; cout << sizeof(char) << "\n"; cout << sizeof(float) << "\n"; cout << sizeof(long) << "\n"; return 0; }
4 1 4 8 8
通过使用此功能,我们可以知道该数据类型的任何变量占用的空间。输出还取决于编译器,因为 16 位编译器将为 int 提供与 32 位编译器不同的值。
我们还可以将此操作应用于表达式 -
#include <bits/stdc++.h> using namespace std; int main() { cout << sizeof(int) << "\n"; cout << sizeof(char) << "\n"; cout << sizeof(float) << "\n"; cout << sizeof(double) << "\n"; cout << sizeof(long) << "\n"; return 0; }
4 4
如您所见,x 之前的值为 4,即使在前缀操作之后,它也恰好保持不变。这都是因为sizeof运算符的原因,因为这个运算符是在编译时使用的,所以它不会改变我们应用的表达式的值。
#include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; // the given array int size = sizeof(arr) / sizeof(int); // calculating the size of array cout << size << "\n"; // outputting the size of given array }
5
这里首先我们计算整个数组的大小或者计算它所占用的内存。然后我们将该数字除以数据类型的 sizeof ;在这个程序中,它是 int。
立即学习“C++免费学习笔记(深入)”;
该运算符的第二个最重要的用例是分配动态内存,因此我们在分配空间时使用 sizeof 运算符。
#include <bits/stdc++.h> using namespace std; int main() { int* ptr = (int*)malloc(10 * sizeof(int)); // here we allot a memory of 40 bytes // the sizeof(int) is 4 and we are allocating 10 blocks // i.e. 40 bytes }
在本文中,我们将讨论 sizeof 运算符的用法及其工作原理。我们还编写了不同类型的用例来查看输出并进行讨论。我们在 C++ 中实现了该运算符的用例。我们可以用其他语言(例如 C、Java、Python 等)编写相同的程序。我们希望本文对您有所帮助。
以上就是使用C++中的sizeof运算符的结果的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号