当前位置:首页C++ > 正文

c++ sizeof

作者:野牛程序员:2025-11-10 19:02:35C++阅读 2247
c++ sizeof
/*
C++ sizeof
作用:获取类型或变量所占字节数
结果为 size_t(无符号整数)
*/

#include <iostream>
using namespace std;

int main() {

    // 基本类型
    cout << "sizeof(char) = " << sizeof(char) << endl;
    cout << "sizeof(int)  = " << sizeof(int)  << endl;
    cout << "sizeof(short)  = " << sizeof(short)  << endl;
    cout << "sizeof(long long)  = " << sizeof(long long)  << endl;
    cout << "sizeof(long) = " << sizeof(long) << endl;
    cout << "sizeof(double) = " << sizeof(double) << endl;

    // 变量
    int x = 10;
    cout << "sizeof(x) = " << sizeof(x) << endl;

    // 数组
    int arr[5];
    cout << "sizeof(arr) = " << sizeof(arr) << endl;          // 总字节
    cout << "元素个数 = " << sizeof(arr) / sizeof(arr[0]) << endl;

    // 指针
    int *p = arr;
    cout << "sizeof(p) = " << sizeof(p) << endl;  // 指针本身字节数(非数组大小)

    return 0;
}


/*
要点:
1) sizeof(类型) 或 sizeof(变量)
2) 返回值为字节数
3) 数组 sizeof = 整体大小;指针 sizeof = 指针大小
*/


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
  • c++ sizeof
  • 相关推荐

    最新推荐

    热门点击