sizeof 运算符:查询对象或类型的大小,在必须知道对象实际大小时使用。

strlen函数:位于头文件<string.h>,查询空终止字节字符串 str 的长度。

语法

  1. sizeof 运算符

    //返回 size_t 类型值
    sizeof(类型);
    sizeof 表达式;
    
    1. 返回 类型 的对象表示的字节大小
    2. 返回 表达式 类型的对象表示的字节大小,不应用隐式转换到表达式

    不能用于函数类型、不完整类型(含void)或位域左值

  2. strlen函数

    size_t strlen(const char *str);
    

    返回空终止字节字符串 str 的长度。

区别

  1. strlen计算的是字符串的字符个数
  2. sizeof计算的是分配空间的字节数
  3. strlen是函数,在程序运行时计算,要求字符串以空字符(‘\0’)结尾
  4. sizeof是关键字,在程序编译时计算,不能用于返回动态分配的内存空间大小

32位机器上,一个指针占4个字节;64位机器上,一个指针占8个字节

d#include <iostream>

using std::cin;
using std::cout;
using std::endl;

void t1() {
    cout << "hello";
}

int t2() {
    return 1;
}

#pragma pack(push) //保存对齐状态
#pragma pack(4)//设定为4字节对齐
class t3 {
    char c;
    int a;
    double b;
};

void t4(int a[10]) {
    cout << sizeof(a) << endl;
}

void t5(char a[10]) {
    cout << sizeof(a) << endl;
}

int main(int argc, char* argv[]) {
    int a[10] = { 0 };
    int* b = new int[10]{ 0 };
    char c[] = "hello,world";
    char d[3] = { 'a', 'b', 'c' };
    t3* i = new t3[10]{ 0, 0 };

    cout << sizeof(a) << endl;  //输出:40     数组所占字节数
    cout << sizeof(b) << endl;  //输出:4      指针所占字节数
    cout << strlen(c) << endl;  //输出:11     第一个'\0'字符前面的字符个数
    cout << sizeof(c) << endl;  //输出:12     字符串(包括'\0'字符)所占字节数
    cout << strlen(d) << endl;  //输出:23     结果随机,无法预料,无意义
    cout << sizeof(d) << endl;  //输出:3      数组所占字节数
    cout << sizeof(int) << endl;//输出:4      int类型的对象所占的字节数
    //cout << sizeof(t1) << endl;   无法将函数作为参数,无论返回值是void还是int之类的
    //cout << sizeof(t2) << endl;
    cout << sizeof(*i) << endl; //输出:16     对象所占的字节数
    //数组传递给函数作参数时,已经隐式转换成指针了
    t4(a);  //输出:4      指针所占字节数
    t4(b);  //输出:4      指针所占字节数

    t5(c);  //输出:4      指针所占字节数
    t5(d);  //输出:4      指针所占字节数
    delete[] i;
    return 0;
}

进阶

空类型的实例仍会占据内存空间,应为声明空类型实例时,必须在内存占有一定空间,否则无法使用这些实例。占多少内存由编译器决定。

Visual Studio中,每个空类型的的实例占用1字节的空间。

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

class Y1 {

};

class Y2 {
public:
    Y2() = default;
    ~Y2() = default;
};

class Y3 {
public:
    virtual ~Y3() {}
};

int main(int argc, char* argv[]) {
    Y1 a;
    Y2 b;
    Y3 c;
    cout << sizeof(a) << endl;  //1
    cout << sizeof(b) << endl;  //1
    cout << sizeof(c) << endl;  //4
    return 0;
}

C++的编译器一旦发现一个类型中有虚函数,就会为该类型生成虚函数表,并在该类型的每个实例中添加一个指向虚函数表的指针。