sizeof()
是 C 语言中的一个运算符,它用于计算数据类型或对象所占用的内存字节数
#include<stdio.h> int main() { printf("Size of int: %lu bytes\n", sizeof(int)); printf("Size of float: %lu bytes\n", sizeof(float)); printf("Size of double: %lu bytes\n", sizeof(double)); printf("Size of char: %lu bytes\n", sizeof(char)); return 0; }
#include<stdio.h> typedef struct { int id; float score; char name[20]; } Student; int main() { printf("Size of Student structure: %lu bytes\n", sizeof(Student)); return 0; }
#include<stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Size of array: %lu bytes\n", sizeof(arr)); printf("Number of elements in the array: %d\n", n); return 0; }
注意事项:
sizeof()
的结果是一个 size_t
类型的值,因此在打印时需要使用 %zu
或 %lu
(在某些编译器中可能需要使用 %u
)格式说明符。sizeof()
计算指针变量的大小时,它将返回指针本身所占用的内存大小,而不是指针所指向的数据的大小。