20191208 指针的妙用,让你掉下巴的对比!

前面写程序的时候出了点问题,经过Martin老师的远程调试,发现错误所在。因为在创建指针的时候没有初始化,将其指向具体的内存。
在这里插入图片描述

// 指针的妙用.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include <Windows.h>
#include <iostream>
#include<stdio.h>
#include<time.h>
#include <assert.h>
using namespace std;
struct hero_status {
	char name[64];
	INT64  iBood;
	INT64  iLevel;
	INT64  iPower;
	char describe[256];
};
struct hero_status Update(struct hero_status hero, int iHeroType) {
	switch (iHeroType) {
	case 1://攻击型英雄
		hero.iBood += 1000;
		hero.iLevel += 1;
		hero.iPower += 100;
		break;
	case 2://防御型英雄
		hero.iBood += 2000;
		hero.iLevel += 1;
		hero.iPower += 50;
		break;
	default:
		break;
	}
	return hero;
};
void Update2(struct hero_status* hero, int iHeroType) {
	assert(hero);
	switch (iHeroType) {
	case 1://攻击型英雄
		hero->iBood += 1000;
		hero->iLevel += 1;
		hero->iPower += 100;
		break;
	case 2://防御型英雄
		hero->iBood += 2000;
		hero->iLevel += 1;
		hero->iPower += 50;
		break;
	default:
		break;
	}
};
int main()
{
	struct hero_status hero;
	strcpy_s(hero.name, "lee");
	hero.iBood = 1000;
	hero.iLevel = 10;
	hero.iPower = 120;

	time_t start, end;
	time(&start);
	for (int i = 0; i < 99999999; i++) {
		hero = Update(hero, 1);
	}

	cout << hero.iBood << endl;
	time(&end);
	cout << "消耗的时间为" << end - start << "秒" << endl;

	///***************采用 指针的方法,神奇的事情发生了,但是没发生,报错了******************************************
	struct hero_status* hero2 = NULL;
	hero2 = (struct hero_status*)malloc(sizeof(struct hero_status));
	strcpy_s(hero2->name, "wang");
	hero2->iBood = 2000;
	hero2->iLevel = 10;
	hero2->iPower = 60;

	time(&start);
	for (int i = 0; i < 99999999; i++)
	{
		Update2(hero2, 2);
	}
	cout << hero2->iBood << endl;
	time(&end);
	cout << "消耗的时间为" << end - start << "秒" << endl;
	free(hero2);

	system("pause");
	return 0;

}

测试结果会让你掉下巴在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值