943,864 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 501
  • C++ RSS
May 26th, 2008
0

vector <string *> v; passed by reference

Expand Post »
Hi, I have the following class and main method:
C++ Syntax (Toggle Plain Text)
  1. class Employee
  2. {
  3. vector<string> v;
  4. string name;
  5. int i;
  6. public:
  7. Employee(){}
  8. Employee(string &n): name(n), i(0){}
  9.  
  10.  
  11. void read(vector<string *> &vec)
  12. {
  13. string n;
  14. for(int i = 0; i !=3; i++)
  15. {
  16. cin>>n;
  17. Employee e(n);
  18. vec.push_back(&n);
  19. }
  20. }
  21. };
  22.  
  23. int main()
  24. {
  25. vector<string *> v;
  26. Employee e;
  27. e.read(v);
  28.  
  29. for(int i = 0; i !=v.size();++i)
  30. {
  31. cout<<"In the main method loop"<<endl;
  32. cout<<*v[i]<<endl;
  33.  
  34. }
  35. cout<<v.size()<<endl;
  36. system("pause");
  37. return 0;
  38. }
Now upon trying to access the vector after I am back in the main method, the program crashes. Does anyone know why?

Many thanks
Last edited by Ancient Dragon; May 26th, 2008 at 3:27 pm. Reason: add code tags
Similar Threads
Reputation Points: 14
Solved Threads: 0
Junior Poster in Training
Grub is offline Offline
60 posts
since Oct 2007
May 26th, 2008
0

Re: vector <string *> v; passed by reference

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: vector<string> vect; and everything will work as you expect.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,951 posts
since Aug 2005
May 26th, 2008
0

Re: vector <string *> v; passed by reference

many thanks
Reputation Points: 14
Solved Threads: 0
Junior Poster in Training
Grub is offline Offline
60 posts
since Oct 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: : error C2228: left of
Next Thread in C++ Forum Timeline: Question about C++ built in functions





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC