sizeof 是 C 和 C++ 中的一个操作符,用于获取数据类型或者变量在内存中所占的字节数。以下是 sizeof 常见的用途以及对应的代码示例:
1. 获取基本数据类型的大小: sizeof 可以用来获取像 int 、 float 、 char 等基本数据类型在当前编译环境下所占用的字节数。
c
#include <stdio.h>
int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of char: %zu bytes\n", sizeof(char));
return 0;
}
1. 计算数组的大小:通过 sizeof 计算数组在内存中占用的总字节数,结合 sizeof 计算单个元素大小,可得到数组元素个数。
c
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
size_t arr_size = sizeof(arr);
size_t element_size = sizeof(arr[0]);
size_t num_elements = arr_size / element_size;
printf("Size of the array: %zu bytes\n", arr_size);
printf("Size of each element: %zu bytes\n", element_size);
printf("Number of elements in the array: %zu\n", num_elements);
return 0;
}
1. 动态内存分配:在使用 malloc 、 calloc 等函数进行动态内存分配时, sizeof 用于确定要分配的内存大小。
c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
perror("Memory allocation failed");
return 1;
}
// 使用分配的内存
for (int i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// 释放内存
free(ptr);
return 0;
}
1. 获取结构体或类的大小:对于自定义的结构体或类, sizeof 可以用来计算它们在内存中所占的字节数。
c
#include <stdio.h>
struct Person {
char name[20];
int age;
float height;
};
int main() {
struct Person p;
size_t struct_size = sizeof(p);
printf("Size of the Person struct: %zu bytes\n", struct_size);
return 0;
}
1. 指针相关: sizeof 用于指针时,得到的是指针变量本身在内存中所占的字节数,而不是指针所指向的数据的大小。
c
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
size_t pointer_size = sizeof(ptr);
printf("Size of the pointer: %zu bytes\n", pointer_size);
return 0;
}
这些示例展示了 sizeof 在不同场景下的常见用途。在实际编程中, sizeof 对于内存管理、数据类型兼容性等方面都非常有用。