MOOC清华《面向对象程序设计》第2章:new/delete运算符实验

测试代码:

#include <iostream>
using namespace std;

int main(){
	for(int i = 0; i < 10; i++){
		switch(i){
			case 0 :
			{	
				int* ptr = new int;
				cout << "case 0 :" << endl;
				cout <<"赋值前 *ptr = " << *ptr << endl;
				cout <<"赋值前 ptr = " << ptr << endl;
				*ptr = 8;
				cout << "直接赋值后 *ptr = " << *ptr << endl;
				cout << "直接赋值后 ptr = " << ptr << endl;
				int a = 9;
				*ptr = a;
				cout << "间接赋值后(1) *ptr = " << *ptr << endl;
				cout << "间接赋值后(1) ptr = " << ptr << endl;
				int b = 10;
				ptr = &b;
				cout << "间接赋值后(2) *ptr = " << *ptr << endl;
				cout << "间接赋值后(2) ptr = " << ptr << endl;
				cout << "sizeof(*ptr) = " << sizeof(*ptr) << endl;
				cout << "sizeof(ptr) = " << sizeof(ptr) << endl << endl;
				delete ptr;
				break;
			}
			case 1 :
			{
				int* array = new int[10];
				cout << "case 1 :" << endl;
				cout << "赋值前 ";
				for(int j = 0; j < 10; j++)
					cout << "array[" << j << "] = " << array[j] << endl;
				cout << endl;
				for(int j = 0; j < 10; j++)
					array[j] = j + 10;
				cout << "赋值后 ";
				for(int j = 0; j < 10; j++)
					cout << "array[" << j << "] = " << array[j] << endl;
				cout << endl;
				cout << "sizeof(array[0]) = " << sizeof(array[0]) << endl;
				cout << "sizeof(array) = " << sizeof(array) << endl;
				delete[] array;
				break;
			}
			default : 
				break;
		}
	}

	return 0;
}

测试结果:


Debug经验:

1,注意指针本身与指针所指变量之间的区别,加星号*与不加星号的区别;

2,case标号后若涉及到变量定义或赋初值,最好每一段case语句段加上一对花括号{},让程序清晰无误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值