accessing arrays from functions

I have a hero structure. In the createHero function, I allow the user to enter how many heroes they want (for an array) and set the attributes. In other functions, sortHeroes and findHero, I have to search through the array. But I declared the array in the create hero function. When I try to move it, I just get errors. I don't know how to make it accessible for all functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
#include <vector>

//create a hero structure that has a name, health and attack property
struct Hero
{
	private: 
		string hName;
		int hHealth;
		int hAttack;		

	public:
		void displayHeroData();
		void setName(string);
		void setHealth(int);
		void setAttack(int);
};

void Hero::displayHeroData()
{
	cout << "Name: " << hName << endl;
	cout << "Health: " << hHealth << endl;
	cout << "Attack: " << hAttack << endl;
};

void Hero::setName(string name)
{
	hName = name;
}

void Hero::setHealth(int health)
{
	if(health > 0)
		hHealth = health;
	else
		hHealth = 100;
}

void Hero::setAttack(int attack)
{
	if(attack > 0)
		hAttack = attack;
	else
		hAttack = 10;
}

//create a function that prompts the user for the Hero's stats and returns a hero
void createHero()
{
	string name;
	int health;
	int attack;
	int num;
	Hero *heroList;
	
	//create an array of heroes that is the exact size of user input
	cout << "How many hero's do you want to create? (greater than 0)" <<endl;
	cin >> num; //user input for array
	heroList = new Hero[num];

	for(int x = 0; x < num; ++x){
	cout << "\n\nWhat is hero " << x+1 <<"'s name?" << endl;
	cin >> name;
	heroList[x].setName(name);
	
	cout << "What is " << name <<"'s health? (greater than 1)" << endl;
	cin >> health;
	heroList[x].setHealth(health);

	cout << "How much damage does " << name <<" deliver?" << endl;
	cin >> attack;
	heroList[x].setAttack(attack);
	
	//returns a hero
	cout << "\n\nHERO INFO:\n" << endl;
	heroList[x].displayHeroData();

	}//end of for loop
}

void sortHeroes()
{
	int sorted;
	
	cout << "Enter 1 to sort heroes by health or 2 to sort heroes by attack." << endl;
	cin >> sorted;

	if (sorted = 1){

	}
	else {

	}
}

void findHero()
{

}

int main()
{
	createHero();	
	sortHeroes();
	findHero();
	
	return 0;
}
Last edited on
Topic archived. No new replies allowed.