首页 > 文章列表 > 使用C++中的sizeof运算符的结果

使用C++中的sizeof运算符的结果

sizeof 运算符 c
438 2023-08-31

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运算符的必要性

< p>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 运算符。

示例< /h2>
#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 等)编写相同的程序。我们希望本文对您有所帮助。