C语言中各数据类型的大小

1. 基本整数类型

  • char:1字节
  • short:通常为2字节
  • int:通常为4字节
  • long:通常为4或8字节
  • long long:通常为8字节

2. 浮点数类型

  • float:通常为4字节
  • double:通常为8字节
  • long double:大小平台相关,通常为8或16字节

3. 指针类型

  • 所有指针类型的大小取决于平台,但通常为4或8字节,分别对应32位和64位系统。

4. 数组类型

  • 数组的大小取决于元素类型和数组的长度。例如,int arr[5] 在典型情况下大小为 4 * 5 = 20 字节。

5. 结构体类型

  • 结构体的大小取决于其成员的大小和对齐方式。对齐方式有时受编译器和编译选项的影响。

6. 枚举类型

  • 枚举类型的大小通常与int相同,即4字节。

在实际编程中,我们可以使用sizeof运算符来获取不同数据类型的大小。以下是一个简单的示例代码:

c 复制代码
#include <stdio.h>

int main() {
    printf("Size of char: %lu bytes\n", sizeof(char));
    printf("Size of short: %lu bytes\n", sizeof(short));
    printf("Size of int: %lu bytes\n", sizeof(int));
    printf("Size of long: %lu bytes\n", sizeof(long));
    printf("Size of long long: %lu bytes\n", sizeof(long long));

    printf("Size of float: %lu bytes\n", sizeof(float));
    printf("Size of double: %lu bytes\n", sizeof(double));
    printf("Size of long double: %lu bytes\n", sizeof(long double));

    printf("Size of pointer: %lu bytes\n", sizeof(int*));

    return 0;
}
bash 复制代码
Size of char: 1 bytes
Size of short: 2 bytes
Size of int: 4 bytes
Size of long: 4 bytes
Size of long long: 8 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of long double: 16 bytes
Size of pointer: 8 bytes

请注意,上述大小是通常情况下的一般规则,实际大小可能会受到编译器、操作系统和硬件架构的影响。因此,在编写代码时,要特别注意处理不同平台和编译器的差异,以确保代码的可移植性和性能。

相关推荐
935963 小时前
机考27 翻译21 单词14
c语言·数据结构·算法
光泽雨3 小时前
C# 中 Assembly 类详解
开发语言·c#
少控科技3 小时前
C#基础训练营 - 02 - 运算器
开发语言·c#
Riemann~~4 小时前
C语言嵌入式风格
c语言·开发语言
Once_day5 小时前
GCC编译(1)入门概述
c语言·编译和链接
zmzb01035 小时前
C++课后习题训练记录Day104
开发语言·c++
爱编码的小八嘎6 小时前
第2章 认识CPU-2.2 16位微处理器(2)
c语言
zmzb01036 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
wjs20246 小时前
Vue3 条件语句
开发语言
_codemonster6 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言