📅  最后修改于: 2023-12-03 15:14:25.057000             🧑  作者: Mango
sizeof()
是一种C语言中的一元运算符,它用于计算变量、类型或表达式的大小。该运算符返回以字节为单位的大小,即占用存储器空间的数量。
sizeof()
的常见使用场景有:
以下是几个示例:
#include <stdio.h>
int main() {
char c;
int i;
float f;
double d;
printf("char size: %ld\n", sizeof(c));
printf("int size: %ld\n", sizeof(i));
printf("float size: %ld\n", sizeof(f));
printf("double size: %ld\n", sizeof(d));
return 0;
}
输出:
char size: 1
int size: 4
float size: 4
double size: 8
#include <stdio.h>
int main() {
int a[10];
char b[5];
printf("array a size: %ld\n", sizeof(a));
printf("array b size: %ld\n", sizeof(b));
return 0;
}
输出:
array a size: 40
array b size: 5
#include <stdio.h>
struct student{
char name[20];
int age;
float score;
};
int main() {
struct student stu;
printf("struct student size: %ld\n", sizeof(stu));
return 0;
}
输出:
struct student size: 28
#include <stdio.h>
int main() {
int *p;
char *q;
printf("pointer p size: %ld\n", sizeof(p));
printf("pointer q size: %ld\n", sizeof(q));
return 0;
}
输出:
pointer p size: 8
pointer q size: 8
需要注意的是,sizeof()
操作返回的是一个size_t
类型的值,该值的大小取决于系统架构,通常是4字节或8字节。
参考文献: