sizeof() 的用法以及注意点

    技术2026-04-22  6

    c语言里的sizeof 是一个计算数据存储空间大小的单目运算符,它返回数据所占的字节个数, 我们可以先来看看MSND里的定义:

    sizeof Operator sizeof expression

    The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t. The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).

    When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays

    这段话大概讲的就是:

    1:sizeof运算符可以得到变量和类型存储空间的大小,大小是以字节为单位的,如一个变量a所占的空间是2个字节,那么sizeof(a) == 2。

    2:如果a是一个数据类型,那么必须加括号表示为sizeof(a)形式,如果a是变量sizeof a也是可以的,但通常都写成sizeof(a)形式。

    3:当sizeof 应用于结构体或变量时,它返回实际所占的空间大小,这个空间可能包括编绎器为了内存对齐而插入的额外的字节。

    4:当sizeof应用于静态多维数组时,它返回整个数据的大小,但sizeof 不能应用于对态分配的数组。

    下面举例说明sizeof的运用

    1. 用于类型

    sizeof(int) //返回4,表示整形数占4个字节,其实这个与系统有关, 一般linux和32位windows都返回4;

    sizeof(char) //返回1;

    struct student { int age; char name[20]; }; sizeof(student);// 返回24;

    struct student { int age; char sex; }; sizeof(student);// 返回8, 这里为什么会返回8呢,一个int占4个字节, 一个char占一个字节, 应该是5个字节啊, 其实不这样的, 编绎器为了更高效率而使得内存对齐, 为char sex另外插入了3个字节, 所以返回8;

    2. 用于变量

    int a = 100;

    sizeof(a);//返回4, 一般根据它的类型而决定它所占空间大小

    long float f = 33.00;

    sizeof(f );//返回8,

    char *p;

    sizeof(p );//返回4, 这里p是一个指针变量,sizeof(p)返回这个指针变量所占的空间大小, 而不是字符p所占的空间大小(一个字符只占一个字节)。

    3. 用于数组

    int int_arr[5]; sizeof(int_arr);//返回20, 而不是5,当用于数组时, 它返回这个数组所点的总字节数, 而不是数组无素的个数;

    最新回复(0)