【面试题3】

考点一: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;
}



 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值