C++ 中 sizeof 运算符的结果


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 运算符的原因,因为此运算符是在编译时使用的,因此它不会更改我们应用的表达式的值。

sizeof 运算符的必要性

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。

此运算符的第二个最重要的用例是分配动态内存,因此我们在分配空间时使用 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 等)中编写相同的程序。希望本文对您有所帮助。

更新于:2021年11月29日

222 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.