Pointer-Pointer-Array not working

Hello,
i'm trying to set up a class, in which I can have an Array which contains names.
The problem is that the number of names(/the size of the array) depends on the input.
I tried stuff like this, which gets an access violation:

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
#include <iostream>
#include <string>
using namespace std;
	

int numberOfPlayers;
string input;

class CPlayers
{
private:
	string players[];

public:

	CPlayers()
	{
		players[0] = "Default";
	}
/*    ~CPlayers() //think i need a dynamic destructor?
        {
        }
*/
	CPlayers(string name)
	{
		for(int i = 0; i < numberOfPlayers; i++)
		{
			players[i] = name;			
		}
	}


	string output()
	{
		for (int i = 0; i < numberOfPlayers; i++)
		{
			return players[i];
		}
	}
};

int main()
{
	cout << "Number of Players:" << endl;
	cin >> numberOfPlayers;
	
	CPlayers **doublePtrPlayers = new CPlayers*[numberOfPlayers];
	
	for (int i = 0; i < numberOfPlayers; i++)
	{
		cout << "Player " << i << ": ";
		cin >> input;
		doublePtrPlayers[i] = new CPlayers(input);
	}

	cout << "Players: " << endl;
	for (int i = 0; i < numberOfPlayers; i++) {
		cout << doublePtrPlayers[i]->output() << endl;
	}


	system("pause");
	return 0;
}

Last edited on
can you use a vector? (include <vector> !!)
vector <string> players;

which will grow to fit if you use push_back() method or you can manually give it a size, and you can resize as needed etc. Vector is a 'variable length array' that avoids the C-style memory management.

the same is true in main, strongly consider
vector<vector<CPlayers> > Players2d;
instead of that ** mess.
which you leaked, you did not destroy your 2d construct.

we can show you any of this, but let us know if you can use them and if so, what you want to do (we can guess at it, but precise words from you help).
Last edited on
@OP You could also design and use your own list - a set of nodes/pointers - a stock C++ learning issue. The list stores info about (completely separate) Player objects described in a Player struct or Player class.

PS: If <vector>'s are used the same separation principle applies ...
Last edited on
Topic archived. No new replies allowed.