考点一:sizeof 计算普通变量所占空间大小
#include<stdio.h>
#include <stdlib.h>
void func(char str[100])
{
printf("4 %d\n",sizeof(str));
}
int main()
{
char str[] = "hello";
char *p = str;
int n = 10;
printf("1 %d\n",sizeof(str)); // sizeof 求的字符串末尾都要有'\0' 所以是6
printf("2 %d\n",sizeof(p)); // p 是一个 char 型的指针 32位系统的 指针和 int 都是 4 个字节
printf("3 %d\n",sizeof(n)) // p 是一个 char 型的指针 32位系统的 指针和 int 都是 4 个字节
func(str); // 当调用 func 函数时 实现的是 地址 的传递 所以程序会在栈上开辟一个 4 个字节的指针指向这个数组
// 所以大小为 4
void *p1 = malloc(100); // p 是一个指向 100 字节堆内存 的指针,指针的大小也是4
printf("5 %d\n",sizeof(p1));
return 0;
}
考点二:使用 sizeof 计算含有虚函数的类对象的空间大小
#include <iostream>
using namespace std;
class Base
{
public:
Base(int x) :a(x)
{
}
void print()
{
cout << "base" << endl;
}
private:
int a; // a 是整型数 占4 个字节
};
class Derived : public Base
{
public:
Derived(int x):Base(x-1),b(x)
{
}
void print()
{
cout << "derived" << endl;
}
private:
int b; // Derived 继承 Base b 也是 4 个字节 4+4=8
};
class A
{
public:
A(int x):a(x)
{
}
virtual void print()
{
cout << "A" << endl;
}
private:
int a; // A中含有 虚 函数 含有一个隐含的虚表指针占4个字节 一共为8 个字节
};
class B:public A
{
public:
B(int x):A(x-1),b(x)
{
}
virtual void print()
{
cout << "B"<<endl;
}
private:
int b; //B 中含有 虚 函数 含有一个隐含的虚表指针占4个字节 一共为 4(int) + 4 (虚表指针) + 4 (继承的inta) = 12 个字节
};
int main()
{
Base obj1(1);
cout << sizeof(obj1)<<endl;
Derived obj2(2);
cout << sizeof(obj2) << endl;
A a(1);
cout << sizeof(a) << endl;
B b(2);
cout << sizeof(b) << endl;
return 0;
}