C++ &vector[] dose not return adress

& array [] does not work . Fail to retrieve the address of a item in a std :: vector. How to get the address of an element in a std :: vector?

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


class point
{
	public:
		int aux;
};

class Class2
{
	public:
		point* aux;
		Class2()
		{
		}
		~Class2()
		{
			aux = NULL;
			delete(aux);
		}
};


void main()
{
	vector<point> vertex;
	vector<Class2> linii;

	point aux_vert;
	Class2 aux_linie;


	for(int i=0 ; i<10 ; i++)
	{
	aux_vert.aux = i;
	vertex.push_back(aux_vert);
	/*aux_linie.aux = &vertex[vertex.size()-1];*/
	linii.push_back(aux_linie);
	linii.back().aux = &vertex[vertex.size()-1]; //my error!!!
	}

	cout<<"vertex:"<<endl;
	for(int i =0;i<vertex.size(); i++)
		cout<<vertex[i].aux<<endl;

	cout<<endl<<endl<<"linii:"<<endl;

	for(int i =0;i<linii.size(); i++)
		cout<<linii[i].aux->aux<<endl;

	system("pause");
}


output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vertex:
0
1
2
3
4
5
6
7
8
9


linii:
0
5787436
2
-842150451
4
5
1472668336
1053
16
9



&vertex[vertex.size()-1]

This code actually works just fine.

The problem is, when you resize the vector (ie: with push_back), vector might have to reallocate the memory buffer, and therefore all those pointers become invalid.
thank you Disch :)
Topic archived. No new replies allowed.