Hello,
I wrote a little program (Create a vector and give it back via pointer.) for a better understanding of pointers.
First it works but when I would like get access to the vector alloacated with "new",
problems occur. For example saving a element is not possible.
#include <iostream>
#include <vector>
using namespace std;
//create vector and pointer
vector<int>*pVector();
vector<int>*pVector()
{
vector<int>*myvector=new vector<int>;
return myvector;
}
//printing vector on the monitor via iterator
void VektorPrint();
void VektorPrint()
{
vector<int>*PrintV=pVector();
vector<int>::iterator it;
for(it=(*PrintV).begin();it!=(*PrintV).end();++it)
{
cout<<*it<<endl;
}
delete PrintV; //Frees the memory allocated with new)
PrintV=0; //pointer to zero so program will crash, if some saves something.
}
int main()
{
*pVector();
//shall save something to the vector allocated on the heap but it doesn't work.
int c=700;
(*pVector()).push_back(c);
VektorPrint();
return 0;
}