C语言sizeof运算符

C语言sizeof运算符教程

C 语言 中,sizeof 运算符用于获取一个 变量 或者 数据类型 所占的内存的字节大小。

C语言sizeof运算符详解

语法

sizeof(type); sizeof(varname);

参数

参数 描述
type 要获取的数据类型
varname 要获取的变量

返回值

返回数据类型或者变量所占的内存大小。

说明

使用 sizeof 运算符,既可以获取指定的数据类型,也可以获取一个变量所占的内存大小。

案例

获取数据类型的字节大小

使用 sizeof 运算符,实现获取数据类型的字节大小

#include <stdio.h> int main(int argc, char **argv) { printf("嗨客网(www.haicoder.net)\n\n"); //使用 sizeof 运算符,实现获取数据类型的字节大小 int sizeofShort = sizeof(short); int sizeofInt = sizeof(int); int sizeofLL = sizeof(long long); int sizeofChar = sizeof(char); int sizeofFloat = sizeof(float); int sizeofDouble = sizeof(double); printf("sizeofShort = %d, sizeofInt = %d, sizeofLL = %d\n", sizeofShort, sizeofInt, sizeofLL); printf("sizeofChar = %d\n", sizeofChar); printf("sizeofFloat = %d, sizeofDouble = %d\n", sizeofFloat, sizeofDouble); }

程序运行后,控制台输出如下:

24_C语言sizeof运算符.png

我们使用了 sizeof 运算符获取了各种数据类型所占的内存的字节大小。

获取变量的字节大小

使用 sizeof 运算符,实现获取变量的字节大小

#include <stdio.h> int main(int argc, char **argv) { printf("嗨客网(www.haicoder.net)\n\n"); //使用 sizeof 运算符,实现获取变量的字节大小 short a = 1; int b = 2; long long c = 3; int sizeofA = sizeof(a); int sizeofB = sizeof(b); int sizeofC = sizeof(c); char d = 'a'; int sizeofD = sizeof(d); float e = 1.223; double f = 1.11111; int sizeofE = sizeof(e); int sizeofF = sizeof(f); printf("sizeofA = %d, sizeofB = %d, sizeofC = %d\n", sizeofA, sizeofB, sizeofC); printf("sizeofD = %d\n", sizeofD); printf("sizeofE = %d, sizeofF = %d\n", sizeofE, sizeofF); }

程序运行后,控制台输出如下:

25_C语言sizeof运算符.png

我们使用了 sizeof 运算符获取了各种数据类型的变量所占的内存的字节大小。

C语言sizeof运算符总结

在 C 语言中,sizeof 运算符用于获取一个变量或者数据类型所占的内存的字节大小。