📜  C中的sizeof运算符(1)

📅  最后修改于: 2023-12-03 15:00:11.501000             🧑  作者: Mango

C中的sizeof运算符

在C语言中,sizeof运算符用于求取指定数据类型的字节数。它可以用于任何数据类型,如基本数据类型、数组、结构体、联合体和函数等。

语法

sizeof运算符有两种形式:

  • sizeof(type)
  • sizeof expression

第一种形式中,type表示数据类型,例如intfloatchar等。第二种形式中,expression表示一个表达式,它可以是任何数据类型。

返回值

sizeof运算符的返回值是一个size_t类型的整数,表示该数据类型占用的字节数。由于不同的编译器实现可能有所不同,因此sizeof运算符返回的值也可能不同。

下面是一些常见数据类型的大小:

| Data type | Size (in bytes) | | ------------- | --------------- | | char | 1 | | short | 2 | | int | 4 | | long | 4 or 8 | | float | 4 | | double | 8 | | long double | 12 or 16 | | pointer | 4 or 8 |

例子

下面是一些sizeof运算符的应用实例:

#include <stdio.h>

int main() {
    int a = 10;
    printf("The size of int is %lu bytes\n", sizeof(int));
    printf("The size of char is %lu bytes\n", sizeof(char));
    printf("The size of short is %lu bytes\n", sizeof(short));
    printf("The size of long is %lu bytes\n", sizeof(long));
    printf("The size of float is %lu bytes\n", sizeof(float));
    printf("The size of double is %lu bytes\n", sizeof(double));
    printf("The size of long double is %lu bytes\n", sizeof(long double));
    printf("The size of pointer is %lu bytes\n", sizeof(int *));
    printf("The size of a is %lu bytes\n", sizeof(a));
    printf("The size of an array is %lu bytes\n", sizeof(int[10]));
    printf("The size of a struct is %lu bytes\n", sizeof(struct { int x; char c; }));
    return 0;
}

输出结果为:

The size of int is 4 bytes
The size of char is 1 bytes
The size of short is 2 bytes
The size of long is 8 bytes
The size of float is 4 bytes
The size of double is 8 bytes
The size of long double is 16 bytes
The size of pointer is 8 bytes
The size of a is 4 bytes
The size of an array is 40 bytes
The size of a struct is 8 bytes
总结

sizeof运算符是C语言的一个非常有用的运算符,它可以帮助程序员检查变量、数组、结构体和函数所占用的内存空间大小。尤其是在进行内存分配和处理时,使用sizeof运算符能够更加准确地估算内存的大小,以防止出现内存溢出等问题。