前面写程序的时候出了点问题,经过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;
}
测试结果会让你掉下巴