| | |
vector <string *> v; passed by reference
Thread Solved |
•
•
Join Date: Oct 2007
Posts: 60
Reputation:
Solved Threads: 0
Hi, I have the following class and main method:
Now upon trying to access the vector after I am back in the main method, the program crashes. Does anyone know why?
Many thanks
C++ Syntax (Toggle Plain Text)
class Employee { vector<string> v; string name; int i; public: Employee(){} Employee(string &n): name(n), i(0){} void read(vector<string *> &vec) { string n; for(int i = 0; i !=3; i++) { cin>>n; Employee e(n); vec.push_back(&n); } } }; int main() { vector<string *> v; Employee e; e.read(v); for(int i = 0; i !=v.size();++i) { cout<<"In the main method loop"<<endl; cout<<*v[i]<<endl; } cout<<v.size()<<endl; system("pause"); return 0; }
Many thanks
Last edited by Ancient Dragon; May 26th, 2008 at 2:27 pm. Reason: add code tags
delete line 17 because it is a do-nothing line.
line 18 is pushing a pointer to an object that disappears from scope as soon as the function returns to main() -- the pointers are immediately invalidated. Why use a vector of pointers anyway? Just do this:
line 18 is pushing a pointer to an object that disappears from scope as soon as the function returns to main() -- the pointers are immediately invalidated. Why use a vector of pointers anyway? Just do this:
vector<string> vect; and everything will work as you expect. The most important thing in the Olympic Games is not to win but to take part, just as the most important thing in life is not the triumph but the struggle. The essential thing is not to have conquered but to have fought well.
-Pierre de Coubertin, The Olympic Creed Inspired by Bishop Ethelbert
-Pierre de Coubertin, The Olympic Creed Inspired by Bishop Ethelbert
![]() |
Similar Threads
Other Threads in the C++ Forum
- Previous Thread: : error C2228: left of
- Next Thread: Question about C++ built in functions
Views: 409 | Replies: 2
| Thread Tools | Search this Thread |
Tag cloud for C++
algorithm api array arrays assignment beginner binary browser c++ c/c++ calculator char class classes code compile compiler constructor conversion convert count delete desktop display dll dynamic encryption error exception file files fstream function functions game givemetehcodez graph gui helpwithhomework homework i/o iamthwee input int integer lazy library linked-list linker list loop looping loops math matrix member memory newbie news number object objects opengl output parameter path pointer pointers problem program programming project random read recursion recursive reference sort sorting spoonfeeding string strings struct student studio template templates text time tree undefined variable vc++ vector video visual win32 window windows winsock






