Having trouble assigning values to a dynamically alocated 2d array of string pointers Edit topicMark as solved

So I'm having trouble with assigning values to this array, here's my code:

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

//Adventurer.cpp

string item = "YEAH";
int rows = 50;
int cols= 2;
int Adventurer::numberOfAdventurers;

Adventurer::Adventurer()
{
	cout << "constructor" << endl;
	
	items = new string**[rows];
	for( int i = 0; i < rows; ++i)
	{
		items[i] = new string*[cols];
	}
	
	for( int i = 0; i < rows; ++i) //The area causing trouble(I think)
	{
		for( int j = 0; j < cols; ++j)
		{
			items[i][j] = &item; 
			cout << *items[i][j] << endl;			
		}		
	}
	
	
    name = "Basic Adventurer";
    maxCarryWeight = 150.0;
    currentCarryWeight = 0;
    currentNumberOfItems = 0;
    maxNumberOfItems = 50;
    health = 100.0;	
     numberOfAdventurers++;
	
}  

//Adventurer.h(incomplete: just the private members)

class Adventurer{
private:
    string*** items;
    string name;
    double maxCarryWeight;
    double currentCarryWeight;
    int currentNumberOfItems;
    int maxNumberOfItems;
    double health;
    static int numberOfAdventurers;



So The values get assigned and output, but at the end i get the error:

*** Error in './adventure.out': free(): invalid pointer: (memory adress)

followed by a Backtrace and Memory Map
Last edited on
closed account (48bpfSEw)
IMHO: avoid pointer acrobatics in C++... use instead maps, vectors or lists to define multi dimensional arrays.
Topic archived. No new replies allowed.